簡體   English   中英

在另一個線程正在執行任務時暫停線程

[英]Pause Thread While Another Thread Is Executing A Task

我創建了一個執行任務的線程,但是我需要暫停我的主線程,直到我的輔助線程結束該任務。

    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

    }

提前致謝。

但是我需要暫停我的主線程,直到我的輔助線程結束任務為止。

這通常是一個壞主意。 更好的解決方案是在執行任務時禁用UI,然后在完成任務時重新啟用它。

TPL和異步/等待使這一過程變得非常簡單。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM