Visual Studio: Can an AutoReset Event for thread waiting be used in a non-threaded method (e.g. inside Button1)?

25 Views Asked by At

I used a MyThreadDone.WaitOne inside a loop in a non-threaded method (that calls and triggers threads, each of which has MyThreadDone.Set at the end of the thread's method), and WaitOne does not seem to be recognized in a non-threaded method?

The code would look like:

'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
1

There are 1 best solutions below

0
AudioBubble On

Here's what I learned, so I am answering in order to help any reader who is interested.

The AutoResetEvent cannot be used in non-threaded methods, e.g., inside a Button1 environment. When WaitOne was triggered inside Button1, everything stopped, including program execution inside Button1, as well as any threads that were already started. In other words, nothing will run (the UI, or threads that were already started).

Therefore, WaitOne and Set can only be used inside threaded methods, i.e., methods that are part of a thread, they cannot be used anywhere you want, especially non-threaded methods or code for which you think you can wait for threads to complete before the next thread starts.