C# Spawn new thread and then wait

落花浮王杯 提交于 2021-02-10 18:16:34

问题


I am very inexperienced using multi-threading techniques, but here is what I have tried:

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

What I am trying to achieve here is to have a thread running and doing work whilst the main thread sleeps, but I am unsure why the above code doesn't work. What happens is that following the first loop (after starting the thread) the ThreadState doesn't seem to change from "Running". I am also curious as to whether there is a more elegant way of doing this.

Anyone know the problem?


回答1:


Thread.Join is a better way to wait for a thread to end.




回答2:


If you're using .Net 4, I'd recommend taking a look at the Task Class. It makes working with multithreading much easier/straight forward.




回答3:


Using the Task class you can do this.

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

task.Wait();



回答4:


What you may be looking for is something more like this:

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

If this is what you're looking for, I'd take a look at the BackgroundWorker class.




回答5:


Thread.Sleep(60000) is executed on the thread that calls it, in this case the main thread. Which is fine, but the "thread" doesn't know how long it has been running for and doesn't know when to actually stop. You need to have an object tell "thread" that it has been running for 60 seconds.

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

This should achieve what you want but isn't really the most elegant way of stopping a thread. A thread should really be ended using callbacks.



来源:https://stackoverflow.com/questions/10185177/c-sharp-spawn-new-thread-and-then-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!