Multithreading Visual Studio:是否可以在非线程方法中使用线程等待的自动重置事件(例如,内部按钮1)?
我在一个非线程方法的循环中使用了一个MyThreadDone.WaitOne(它调用并触发线程,每个线程的方法末尾都设置了MyThreadDone.WaitOne),而WaitOne似乎在一个非线程方法中无法识别 代码如下所示:Multithreading Visual Studio:是否可以在非线程方法中使用线程等待的自动重置事件(例如,内部按钮1)?,multithreading,visual-studio,methods,autoresetevent,Multithreading,Visual Studio,Methods,Autoresetevent,我在一个非线程方法的循环中使用了一个MyThreadDone.WaitOne(它调用并触发线程,每个线程的方法末尾都设置了MyThreadDone.WaitOne),而WaitOne似乎在一个非线程方法中无法识别 代码如下所示: 'Set the global AutoReset Event Public MyThreadDone As New AutoResetEvent(False) 'Initially set the thread waiting to .Set in e.g. For
'Set the global AutoReset Event
Public MyThreadDone As New AutoResetEvent(False)
'Initially set the thread waiting to .Set in e.g. Form1_Load
MyThreadDone.Set
'Somewhere in e.g. Button1
For i As Integer = 1 To 5
Dim classwiththread as New ClassWithThreadedMethod()
MyThreadDone.WaitOne
Next
Public Class ClassWithThreadedMethod
Sub New()
Dim t As New Thread(AddressOf MyMethod)
t.Start()
End Sub
Sub MyMethod()
.
'Do the work
.
MyThreadDone.Set
End Sub
End Class
以下是我所学到的,所以我的回答是为了帮助任何感兴趣的读者 AutoResteEvent不能在非线程方法中使用,例如在Button1环境中。当在Button1内触发WaitOne时,一切都停止了,包括Button1内的程序执行,以及所有已经启动的线程。换句话说,不会运行任何东西(UI或已启动的线程)
因此,WaitOne和Set只能在线程方法内部使用,即作为线程一部分的方法,它们不能在您想要的任何地方使用,特别是非线程方法或代码,您认为可以在下一个线程启动之前等待线程完成 WaitOne方法没有理由不在调用时可用。您可能已经知道这一点,但请注意,在应用程序的UI线程中调用任何线程都会有阻塞的副作用。事实上,当您阅读AutoResteEvent时,很明显,如果当前线程是UI,使用WaitOne将停止当前线程,即UI。这是我在非线程的Button1中简单使用Waitone时注意到的-->从Button1内部调用和启动的线程完全停止了处理。查看Invoke和InvokeRequired方法/属性以从UI线程调用线程方法。它确保了正确的上下文切换,因此从正确的线程调用方法。谢谢-我已经有很多委托从线程修改UI控件。