2010-06-11 123 views
0

我已經寫了一個線程,我已經開始使用start方法,但是我無法知道線程何時執行了方法並銷燬了線程對象。.net線程執行

_ProgressThread = New Thread(AddressOf ExecProc) 
_ProgressThread.IsBackground = False 
_ProgressThread.Start() 

//the flow of execution should come here only after the thread has executed the method 
//but its coming and executing this line after the thread has started. 
Me.MainInit() 
_ProgressThread = Nothing 

什麼是最好的方法。請幫忙。另外我想在線程完成執行方法後調用一個方法。

回答

1

有兩種(或更多)可能的方式。一種是使用ManualResetEvent如下:

_Event = New ManualResetEvent(False); <-- Create event globally 

然後,在你的線程的啓動代碼:

_ProgressThread = New Thread(AddressOf ExecProc) 
_ProgressThread.IsBackground = False 
_ProgressThread.Start() 

//the flow of execution should come here only after the thread has executed the method 
//but its coming and executing this line after the thread has started. 
_Event.WaitOne(); <-- This waits! 
_Event.Close(); <-- This closes the event 

Me.MainInit() 
_ProgressThread = Nothing 

在你的線程的方法,你必須在所有情況下方法返回之前調用_Event.Set(),否則你的應用程序將被阻止。

另一種方法是必須在完成時線程調用委託。您想要在線程完成後執行的代碼(Me.MainInit())將進入委託方法。這實際上是相當優雅的。

例如:

public delegate void ThreadDoneDelegate(); 

private void ExecProc() 
{ 
    ThreadDoneDelegate del = new ThreadDoneDelegate(TheThreadIsDone); 

    ... // Do work here 

    this.Invoke(del); 
} 

private void TheThreadIsDone() 
{ 
    ... // Continue with your work 
} 

對不起,我不磺化聚醚醚酮VB流利,所以你必須給這個小C#代碼段:-)

+0

沒問題。我理解這兩個世界。不管怎麼說,還是要謝謝你。 – 2010-06-11 09:54:34

+0

我有一個問題,我在線程方法內設置了一個進度條的值,所以每次我在寫入_event.set()之前設置進度條值,並從方法返回並執行maininit()方法。 – 2010-06-11 10:24:42

+0

更新進度欄時,不要調用_event.Set()。你只能在你的線程方法真正退出之前調用它(無論是因爲錯誤還是因爲它的完成)。 – 2010-06-11 10:34:16

2

首先,將變量設置爲Nothing不會破壞對象。其次,如果這是一個實例變量,但在啓動線程後你不需要它,爲什麼要保持它呢?如果它是一個局部變量,就讓它掉到範圍之外。

基本上,這不取決於你「摧毀」這個對象 - 只要你對它感興趣,你只需要保留一個引用即可。

如果這沒有幫助,請提供更多詳細信息。

+0

我想要的線程執行完該方法後執行的方法,但線程執行完畢之前,該函數被調用。 – 2010-06-11 09:35:48

+0

@Soham:最簡單的事情不是直接爲線程啓動「ExecProc」,而是調用ExecProc然後執行其他方法的方法。 – 2010-06-11 09:45:30

2

轉換如果我理解正確的話,你想等待一個線程完成。這可以通過joining的線程acomplished:

_ProgressThread = New Thread(AddressOf ExecProc) 
_ProgressThread.IsBackground = False 
_ProgressThread.Start() 

// you can do parallel work here 

// wait for the thread to finish 
_ProgressThread.Join(); 
+0

你說的很對,但是Thorsten Dittmar的回答正常,唯一的問題是我的進度條UI沒有更新,應用程序正在進入死鎖狀態。你能根據他的回答給我提出建議嗎?不管怎麼說,還是要謝謝你。 – 2010-06-11 11:48:23

+0

當你可以使用線程obj時,創建一個事件是一種矯枉過正(恕我直言)。 無論如何,我想你正在嘗試更新線程內的進度條吧?如果是這樣,您需要使用control.InvokeRequired /control.Invoke()成員將調用回調到UI線程。 欲瞭解更多信息,請參閱http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired(v=VS.100).aspx – Vagaus 2010-06-11 12:14:14