0
点赞
收藏
分享

微信扫一扫

C#多线程报错:The destination thread no longer exists.


WinForm,C#多线程报错:

System.ComponentModel.InvalidAsynchronousStateException: 'An error occurred invoking the method.  The destination thread no longer exists.'

研究一番,找到了原因:

有问题的写法:

new Thread(new ThreadStart(scan)).Start();

private void scan()
{      
    //...
    addForm(name);  //该方法内部会另外启动Thread         
    Thread.Sleep(3000);    
    new Thread(new ThreadStart(scan)).Start();
}

原因,一开始用独立线程调用了scan方法,称之为Thread1, 然后scan方法内部又启动了独立线程,称之未Thread1-1,Thread1-2,等等。然后scan方法执行结束之后,Thread1结束,为了要让scan方法循环执行,再次启动另外一个Thread。此时Thread1已经结束,而Thread1-1,1-2是依赖于它的,所以Thread1-1,1-2就报错了:The destination thread no longer exists.

解决办法,修改写法:

new Thread(new ThreadStart(scan)).Start();

private void scan()
{   
    while(true)
    {
        //...
        addForm(name);  //该方法内部会另外启动Thread         
        Thread.Sleep(3000);    
        scan();
    }
}

就本例而言,destination thread no longer exists的问题是解决了。

举报

相关推荐

0 条评论