在另一个线程执行任务时暂停线程

时间:2014-07-03 17:46:58

标签: c# .net multithreading winforms

我创建了一个执行任务的线程,但我需要暂停我的主线程,直到我的辅助线程结束任务。

    private void AquilesPL_Load(object sender, EventArgs e)
    {
       ThreadStart ts = new ThreadStart(RunTask)
       Thread t = new Thread(ts);
       t.Start();
       SomeFunction1();
       SomeFunction2();
       //I need to pause the main thread here, if runtask() continue working
       //if runt task ends, this main thread must to continue.
       ReadFile();
       CloseProgram();
    }
    private void RunTask()
    {
        //Some code that write a file 
        //RunTaskfunction ends, and i have to continue 
    }

    private void ReadFile()
    {
        //Reading the file, this file has been written by RunTask

    }

提前致谢。

1 个答案:

答案 0 :(得分:7)

  

但我需要暂停我的主线程,直到我的辅助线程结束任务。

这通常是一个坏主意。更好的解决方案是在任务执行时禁用UI,然后在完成任务时重新启用它。

TPL和async / await使这相当简单。例如:

private async void AquilesPL_Load(object sender, EventArgs e)
{
   var task = Task.Run(() => RunTask());
   SomeFunction1();
   SomeFunction2();

   // Disable your UI controls

   await task; // This will wait until the task completes, 
               // but do it asynchronously so it does not block the UI thread

   // This won't read until the other task is done
   ReadFile();

   // Enable your UI controls here
}

如果您不能使用C#5,可以通过.NET 4和TPL执行此操作:

private void AquilesPL_Load(object sender, EventArgs e)
{
   var task = Task.Factory.StartNew(() => RunTask());

   SomeFunction1();
   SomeFunction2();

   // Disable your UI controls

   task.ContinueWith(t =>
   {
       // This won't read until the other task is done
       ReadFile();

       // Enable your UI controls here
   }, TaskScheduler.FromCurrentSynchronizationContext());
}