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的问题是解决了。

相关推荐
隐积10 小时前
3.1.7.Qt容器大家族(3):QVariant——万能盒子
开发语言·qt
名字还没想好☜13 小时前
Next.js ‘use client‘ 到底加在哪:Server/Client Components 边界与常见报错
开发语言·前端·javascript·react·next.js
初级代码游戏14 小时前
iOS开发 Swift 速记1:变量和基本数据类型
开发语言·ios·swift
海盗123414 小时前
微软技术周报 ——2026-08-03
后端·python·microsoft·c#·.netcore
酷在前行15 小时前
【R生态】PERMANOVA 进阶实战:距离选择、PERMDISP、两两比较与受限置换(保姆级教程)
开发语言·r语言
cxr82815 小时前
Graphify vs GitNexus vs CodeGraph — 三工具架构深度对比
开发语言·架构·知识图谱
废弃的小码农16 小时前
功能测试--Day07--Python编程基础
开发语言·python
fengci.16 小时前
Microweber CMS 未授权路径穿越漏洞(CVE-2026-65694)
android·开发语言·前端·学习·php
程序员zgh17 小时前
C++ 拷贝赋值运算符 详解
c语言·开发语言·c++
念何架构之路17 小时前
restartmanager-重启管理子系统
java·开发语言