.NET 1.0 THERETPOOL问题
-
23-10-2019 - |
题
我正在尝试产生一个线程,以照顾应花费不到3秒钟的Dowork任务。在Dowork内部,它需要15秒。我想中止陶氏并将控件转回主线程。我已将代码复制如下,并且不起作用。它仍然没有流交陶库克,而是完成陶库,然后将控件转回主线程。我究竟做错了什么?
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
private static System.Threading.ManualResetEvent[] resetEvents;
[STAThread]
static void Main(string[] args)
{
resetEvents = new ManualResetEvent[1];
int i = 0;
resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork),(object)i);
Thread.CurrentThread.Name = "main thread";
Console.WriteLine("[{0}] waiting in the main method", Thread.CurrentThread.Name);
DateTime start = DateTime.Now;
DateTime end ;
TimeSpan span = DateTime.Now.Subtract(start);
//abort dowork method if it takes more than 3 seconds
//and transfer control to the main thread.
do
{
if (span.Seconds < 3)
WaitHandle.WaitAll(resetEvents);
else
resetEvents[0].Set();
end = DateTime.Now;
span = end.Subtract(start);
}while (span.Seconds < 2);
Console.WriteLine(span.Seconds);
Console.WriteLine("[{0}] all done in the main method",Thread.CurrentThread.Name);
Console.ReadLine();
}
static void DoWork(object o)
{
int index = (int)o;
Thread.CurrentThread.Name = "do work thread";
//simulate heavy duty work.
Thread.Sleep(15000);
//work is done..
resetEvents[index].Set();
Console.WriteLine("[{0}] do work finished",Thread.CurrentThread.Name);
}
}
解决方案
全部 汇总线程 是背景线程,这意味着当应用程序的前景线端末端时它们会自动终止。
我更改了您的循环,并删除了重点。
//abort dowork method if it takes more than 3 seconds
//and transfer control to the main thread.
bool keepwaiting = true;
while (keepwaiting)
{
if (span.Seconds > 3)
{
keepwaiting = false;
}
end = DateTime.Now;
span = end.Subtract(start);
}
其他提示
[STAThread]
是单线公寓。尝试 [MTAThread]
这是多线公寓。
不隶属于 StackOverflow