简体   繁体   English

等待后台线程在C#中完成处理的最佳方法

[英]Best way to wait for a background thread to finish processing in C#

I have a background thread. 我有一个后台主题。 If the background thread is busy, I want to wait for it to finish its work and then continue with next request. 如果后台线程忙,我想等待它完成其工作,然后继续下一个请求。 I have implemented it in the following way. 我已通过以下方式实现它。 Process is the name of the background thread. Process是后台线程的名称。

 if (process.IsBusy)
 {
     do
     {
         isProcessBusy = process.IsBusy;
     } while (isProcessBusy == false);

     SetIsDirty(status, GetContext());
 }
 else
 {
     SetIsDirty(status, GetContext());
 }

Is this the best way or are there other ways to implement this kind of logic? 这是最好的方式还是有其他方法来实现这种逻辑?

The Thread class has a method named Join that blocks until the thread on which it is being called exits. Thread类有一个名为Join的方法,它阻塞直到调用它的线程退出。
Take a look at here . 看看这里

This is not recommended at all. 根本不建议这样做。 This way you would always be utilising your CPU without doing any actual work. 通过这种方式,您可以始终在不使用任何实际工作的情况下使用CPU。

If you want to use the same approach, use some Wait Handles or Sleep before you check if the thread is active. 如果要使用相同的方法,请在检查线程是否处于活动状态之前使用一些等待句柄或睡眠。

However, I would recommend checking this article for getting a better understanding on background threads and different synchronisation approaches. 不过,我会建议您检查文章为获得在后台线程和不同的同步方式更好的理解。

OR 要么

you can also consider using ThreadPool for handling the background tasks. 您还可以考虑使用ThreadPool来处理后台任务。 Here is an example from Microsoft for the same. 以下是微软的一个例子

You can use AutoResetEvent for this: 您可以使用AutoResetEvent

Example: 例:

AutoResetEvent resetEvent = new AutoResetEvent(false);

private void StartProcess()
{
    new Thread(DoProcess).Start();
}

private void DoProcess()
{
    List<String> list = new List<String>() { 
        "Value 1",
        "Value 2",
        "Value 3",
        "Value 4",
        "Value 5",
    };

    foreach (String item in list)
    {
        process.RunWorkerAsync(item);

        if (!resetEvent.WaitOne())
        {
            // Some exception
            break;
        }
        resetEvent.Reset();
    }
}

private void process_DoWork(object sender, DoWorkEventArgs e)
{
    Debug.WriteLine(e.Argument.ToString());
    Thread.Sleep(1000);
}

private void process_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    resetEvent.Set();
}

Is you want to wait until some task is done, use Thread.Sleep(0) or Thread.Sleep(100) to avoid burning 100 percent of the CPU core just for waiting one flag to be raised. 是否要等到某个任务完成后,使用Thread.Sleep(0)或Thread.Sleep(100)来避免烧掉100%的CPU内核只是为了等待一个标志被引发。

There are methods with events and semaphores, but this one is simple and it won't hurt a bit. 有一些事件和信号量的方法,但这个方法很简单,不会有点伤害。

The way to block one thread, waiting the end of another thread, is called locking. 阻塞一个线程,等待另一个线程结束的方法称为锁定。 C# allows us to lock our code with either a Monitor class or a lock { } construct. C#允许我们使用Monitor类或lock {}构造来锁定代码。 Have a look to this. 看看这个。

For exemple: 举个例子:

 Class1()
            {
                  // construct two threads for our demonstration;
                  Thread thread1 = new Thread(new ThreadStart(DisplayThread1));
                  Thread thread2 = new Thread(new ThreadStart(DisplayThread2));

                  // start them
                  thread1.Start();
                  thread2.Start();
            }

        void DisplayThread1()
        {
              while (_stopThreads == false)
              {
                  // lock on the current instance of the class for thread #1
                    lock (this)
                    {
                          Console.WriteLine("Display Thread 1");
                          _threadOutput = "Hello Thread1";
                          Thread.Sleep(1000);  // simulate a lot of processing
                          // tell the user what thread we are in thread #1
                          Console.WriteLine("Thread 1 Output --> {0}", _threadOutput);
                    } // lock released  for thread #1 here
              } 
        }

        void DisplayThread2()
        {
              while (_stopThreads == false)
              {

                  // lock on the current instance of the class for thread #2
                    lock (this)
                    {
                          Console.WriteLine("Display Thread 2");
                          _threadOutput = "Hello Thread2";
                          Thread.Sleep(1000);  // simulate a lot of processing
                          // tell the user what thread we are in thread #1
                          Console.WriteLine("Thread 2 Output --> {0}", _threadOutput);
                    }  // lock released  for thread #2 here
              } 
        }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM