【问题标题】:Pause Thread While Another Thread Is Executing A Task当另一个线程正在执行任务时暂停线程
【发布时间】:2014-07-03 17:46:57
【问题描述】:

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

    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

    }

提前致谢。

【问题讨论】:

  • EventArgs 表明您做错了。
  • 您正在使用或可以使用哪个 C# / .NET 版本?应用程序的类型是什么(WinForms?)?
  • 您永远不会“暂停” GUI 应用程序的主线程。除了死锁或无功能的冻结用户界面之外,这并没有完成任何事情。使用控件的 Enabled 属性来防止它们在工作完成时被使用。一个指示进度的对话框是一个显而易见的选择。

标签: c# .net multithreading winforms


【解决方案1】:

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

这通常是个坏主意。更好的解决方案是在任务执行时禁用 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());
}

【讨论】:

  • 我正要写同样的答案,所以+1
  • “将阻止”一词在这里可能传达了错误且相互矛盾的信息。并非所有 WinForms 用户都(能够)使用 C#5。
  • 太棒了。看来 OP 需要答案的第二部分。
  • RunTask 进程运行antivirusscaner,并从防病毒日志中收集信息,它需要1 或3 分钟。 Runtask 可能比其他任务先结束。
  • 这是相关信息,将其添加(编辑)到问题中。但这与这个答案并不冲突。
猜你喜欢
  • 2019-01-12
  • 1970-01-01
  • 2011-12-27
  • 1970-01-01
  • 2013-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多