2010-06-11 124 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