gpt4 book ai didi

c# - .NET 1.0 线程池问题

转载 作者:太空宇宙 更新时间:2023-11-03 14:29:33 25 4
gpt4 key购买 nike

我正在尝试生成一个线程来处理应该少于 3 秒的 DoWork 任务。在 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);
}
}

最佳答案

全部pooled threads是后台线程,这意味着它们会在应用程序的前台线程结束时自动终止。

我更改了您的循环并删除了 resetEvents。

     //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);
}

关于c# - .NET 1.0 线程池问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2962519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com