Stop all threads if an error is detected in one of them

I am trying to implement multithreading in an application. An application needs to create a variable number of threads by passing variables. I can easily create threads, but I'm trying to figure out how to stop all threads at once, and if an error gets into any of these threads, stop them all.

My current solution is to enclose the functions in a loop that checks if the boolean is "True", in which case the flow continues. If there is an error, I change the value to "False", and all threads stop. Similarly, if I want to stop threads manually, I can set the value to false from the function.

Is there a better solution for this, since the main problem is that the threads must go to the end of the cycle before they stop completely?

+4
source share
3 answers

Starting threads while True block should be in order. After it is false, you can simply iterate over threads and call thread.abort (), although sometimes using abort is not a good idea. Using a list of threads can be helpful. I do not know how you create your threads, but this should be easy to understand.

Dim listThreads As List(Of Threading.Thread) 'create/instantiate your threads adding them to the collection something like the following For i = 1 To numberofthreadsyouneed Dim tempThread As Threading.Thread = New Threading.Thread tempThread.Start() tempThread.Add(tempThread) next 

Instead of using the while block, just try catch. inside catch list iteration to interrupt threads

 Catch ex As Exception For each Thread in listThreads Thread.Abort() Next end Try 
+2
source

try it

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim foo As New List(Of Threading.Thread) Threading.Interlocked.Exchange(stopRun, 0L) For x As Integer = 1 To 5 'start five threads Dim t As New Threading.Thread(AddressOf workerThrd) t.IsBackground = True t.Start() foo.Add(t) 'add to list Next Threading.Thread.Sleep(2000) 'wait two seconds Threading.Interlocked.Increment(stopRun) 'signal stop For Each t As Threading.Thread In foo 'wait for each thread to stop t.Join() Next Debug.WriteLine("fini") End Sub Dim stopRun As Long = 0L Private Sub workerThrd() Do While Threading.Interlocked.Read(stopRun) = 0L Threading.Thread.Sleep(10) 'simulate work Loop Debug.WriteLine("end") End Sub 
+2
source

If you need more control

Here

- This is a pretty nice thing called Tasks , which they come out some time ago. This gives you a bit more control over your threads.

Hope this helps.

+1
source

Source: https://habr.com/ru/post/1493265/


All Articles