C# 多线程处理等待及线程超时问题
最近在写个多线程自动化脚本操作,但是发现会出现线程卡死的现象,因此需要去设置线程超时时间,经过一番研究总结了以下几行代码这里贴出部分来作为记录和参考/// <summary>/// 多个线程/// </summary>public static void MultipleThreads(int th)...
·
最近在写个多线程自动化脚本操作,但是发现会出现线程卡死的现象,因此需要去设置线程超时时间,经过一番研究总结了以下几行代码这里贴出部分来作为记录和参考
/// <summary>
/// 多个线程
/// </summary>
public static void MultipleThreads(int th)
{
CountdownEvent latch = new CountdownEvent(th);
for (int i = 0; i < th; i++)
{
try
{
var cts = new CancellationTokenSource();
var thread = new Thread(() =>
{
try
{
SingleThread();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
latch.Signal();
});
//事件注册
cts.Token.Register(() =>
{
if (thread.ThreadState != System.Threading.ThreadState.Stopped)
{
try
{
thread.Abort();
BF bf = new BF();
ConfigBase.线程超时 = bf.TongJi(ConfigBase.线程超时);
latch.Signal();
Console.WriteLine("线程超时,已自动kill 掉!");
}
catch
{
}
}
});
//设置单个线程最大超时时间
cts.CancelAfter(ConfigBase.thread_timeout);
thread.Start();
Thread.Sleep(2000);
}
catch (Exception ex)
{
Console.WriteLine("线程错误,错误原因:{0}",ex.Message.ToString());
}
}
latch.Wait();
latch.Reset();
latch.Dispose();
BsExit();
Thread.Sleep(3000);
这里说明一下 CountdownEvent latch = new CountdownEvent(th); 是用来等待所有线程执行结束的,其中在线程里面去注册线程超时的时间,var cts = new CancellationTokenSource(); 就是用来注册线程超时的
//事件注册
cts.Token.Register(() =>
{
if (thread.ThreadState != System.Threading.ThreadState.Stopped)
{
try
{
thread.Abort();
Console.WriteLine("线程超时,已自动kill 掉!");
}
catch
{
}
}
});
//设置单个线程最大超时时间
cts.CancelAfter(1000);
thread.Start();
仅供参考
更多推荐



所有评论(0)