1

我对使用多线程技术非常缺乏经验,但这是我尝试过的:

Thread thread = null;

for (int minute = 0; minute < 60; minute++)
{
    Thread.Sleep(60000);

    if (thread != null)
    {
        while (thread.ThreadState == ThreadState.Running) { }
    }

    thread = new Thread(delegate()
    {
        // Do stuff during the next minute whilst the main thread is sleeping.
    });
    thread.Start();
}

我在这里想要实现的是让一个线程在主线程休眠时运行并工作,但我不确定为什么上面的代码不起作用。发生的情况是,在第一个循环之后(在启动线程之后),ThreadState 似乎没有从“正在运行”改变。我也很好奇是否有更优雅的方式来做到这一点。

有谁知道这个问题?

4

5 回答 5

4

Thread.Join是等待线程结束的更好方法。

于 2012-04-17T04:54:45.920 回答
2

如果您使用的是 .Net 4,我建议您查看Task Class。它使多线程工作变得更加容易/直接。

于 2012-04-17T05:02:39.093 回答
1

使用Task类你可以做到这一点。

Task task = Task.Factory.StartNew(() =>
  {
    // Do stuff here.
  });

task.Wait();
于 2012-04-17T13:37:12.480 回答
0

Thread.Sleep(60000) 在调用它的线程上执行,在这种情况下是主线程。这很好,但是“线程”不知道它已经运行了多长时间,也不知道什么时候真正停止。您需要有一个对象告诉“线程”它已经运行了 60 秒。

Thread thread = null;

for (int minute = 0; minute < 60; minute++)
{
    if (thread != null)
    {
        while (thread.ThreadState == ThreadState.Running) { }
    }

    thread = new Thread(delegate()
    {
        try
        {
            // Do stuff during the next minute whilst the main thread is sleeping.
        }
        catch (ThreadAbortException ex)
        {
        }
    });
    thread.Start();
    Thread.Sleep(60000);
    thread.Abort();
}

这应该可以实现您想要的,但并不是真正停止线程的最优雅的方式。一个线程真的应该使用回调结束。

于 2012-04-17T05:01:00.780 回答
0

您可能正在寻找的是更像这样的东西:

Thread thread = new Thread(delegate()
    {
        // Something that takes up to an hour
    });
thread.Start();

for (int minute = 0; minute < 60; minute++)
{
    Thread.Sleep(60000);
    if (thread.IsAlive)
        Console.WriteLine("Still going after {0} minute(s).", minute);
    else
        break; // Finished early!
}

// Check if it's still running
if (thread.IsAlive)
{
    Console.WriteLine("Didn't finish after an hour, something may have screwed up!");
    thread.Abort();
}

如果这是您正在寻找的,我会看看BackgroundWorker类。

于 2012-04-17T05:08:03.447 回答