【发布时间】:2011-02-27 02:20:55
【问题描述】:
我正在尝试生成一个线程来处理 DoWork 任务,该任务应该花费不到 3 秒的时间。在 DoWork 内部需要 15 秒。我想中止 DoWork 并将控制权转移回主线程。我已将代码复制如下,但它不起作用。它不会中止 DoWork,而是完成 DoWork,然后将控制权转移回主线程。我做错了什么?
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);
}
}
【问题讨论】:
-
如果你真的在使用 VS2002,那么你做错的一件事就是使用了八年的软件。你为什么不至少运行 .NET 1.1 SP1?
-
使用的 .net 版本不取决于我。
标签: c# multithreading .net-1.0