How can BackgroundWorker get values ​​from a user interface thread while it is running?

I use BackgroundWorker to perform heavy tasks, so the UI thread is not blocked. Although BackgroundWorker can send values ​​to the user interface stream using a progress diagram, how can BackgroundWorker get some values ​​from the user interface stream?

Either by asking him, or just by a UI thread sending some values ​​to BackgroundWorker?

Just accessing a user interface thread variable, such as UIForm.x in BackgroundWorker, doesn't work, it doesn't seem to have access to user interface variables.

Many thanks

+2
source share
1 answer

Threads other than the user interface thread do not have access to the user interface. You probably started BackgroundWorker with worker.RunWorkerAsync() . You can also run it with worker.RunWorkerAsync(someObject) . While the worker is working, you cannot transfer new objects, but you can change the contents of the object itself. Because object types are reference types, the user interface thread and the workflow will see the same object content.

 Imports System.ComponentModel Imports System.Threading Class BgWorkerCommunication Private _worker As BackgroundWorker Private Class WorkParameters Public text As String End Class Public Sub DoRun() Dim param = New WorkParameters() _worker = New BackgroundWorker() AddHandler _worker.DoWork, New DoWorkEventHandler(AddressOf _worker_DoWork) AddHandler _worker.RunWorkerCompleted, New RunWorkerCompletedEventHandler(AddressOf _worker_RunWorkerCompleted) param.text = "running " _worker.RunWorkerAsync(param) While _worker.IsBusy Thread.Sleep(2100) param.text += "." End While End Sub Private Sub _worker_RunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Console.WriteLine("Completed") End Sub Private Sub _worker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Dim param = DirectCast(e.Argument, WorkParameters) For i As Integer = 0 To 9 Console.WriteLine(param.text) Thread.Sleep(1000) Next End Sub End Class 
+4
source

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


All Articles