2014-07-03 159 views
0

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

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 

    } 

在此先感謝。

+2

EventArgs的是,你這樣做是錯誤的指標。 –

+0

您正在使用什麼C#/ .NET版本,或者您可以使用?什麼是應用程序的類型(WinForms?)? –

+1

您從不「暫停」GUI應用程序的主線程。除了死鎖或非功能性凍結的用戶界面,這並沒有完成任何事情。使用控件的Enabled屬性可防止在工作完成時使用它們。指示進度的對話是一個明顯的選擇。 –

回答

7

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

這通常是一個壞主意。更好的解決方案是在任務執行時禁用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()); 
} 
+0

我正要寫相同的答案,所以+1 – ken2k

+0

單詞「將阻止」可能傳達一個錯誤和衝突的消息在這裏。並不是所有的WinForms用戶都(可以)使用C#5。 –

+0

@HenkHolterman好點,還搭上了.NET 4的版本 –

相關問題