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

WinForm,C#多线程报错:

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

研究一番,找到了原因:

有问题的写法:

cs 复制代码
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.

解决办法,修改写法:

cs 复制代码
new Thread(new ThreadStart(scan)).Start();

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

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

相关推荐
我的运维人生4 分钟前
Python技术深度探索:从基础到进阶的实践之旅(第一篇)
开发语言·python·运维开发·技术共享
Bonne journée5 分钟前
‌在Python中,print(f‘‘)是什么?
java·开发语言·python
Two_brushes.18 分钟前
C++ list 容器类的模拟实现
开发语言·c++·list
王俊山IT33 分钟前
C++学习笔记----8、掌握类与对象(五)---- 嵌套类与类中枚举
开发语言·c++·笔记·学习
Bruce_Li_Q33 分钟前
C语言贪吃蛇
c语言·开发语言
RangoLei_Lzs1 小时前
C++模版SFIANE应用踩的一个小坑
java·开发语言·ui
qq_213157891 小时前
(c#)unity中sqlite多线程同时开启事务会导致非常慢
数据库·sqlite·c#
北极无雪1 小时前
Spring源码学习(拓展篇):SpringMVC中的异常处理
java·开发语言·数据库·学习·spring·servlet
VXbishe1 小时前
(附源码)基于springboot的“我来找房”微信小程序的设计与实现-计算机毕设 23157
java·python·微信小程序·node.js·c#·php·课程设计
猿小猴子1 小时前
Python3 爬虫 中间人爬虫
开发语言·爬虫·python