Remove the need for Invoke () by accessing the stream library

In the class library that I am writing, I have a method that allows the library to go and do some things in another thread that does something like:

public void DoStuffAsync(AP p) { this.Running = true; this.Cancel = false; ParameterizedThreadStart threadStart = new ParameterizedThreadStart(DoStuff); Thread procThread = new Thread(threadStart); procThread.Start(p); } 

I also have a series of events declared on an interface that a developer can connect, such as StatusUpdate and ProgressUpdate. I am currently writing a small test application (in WPF, although I expect the same behavior in WinForms) that calls DoStuffAsync () and then updates the progress bar and label.

Unfortunately, the 1st pass I have an error, the usual thread is not the one that owns the controls. I would like the user to not invoke Invoke () within the user interface and just subscribe to events and make them work.

So the question is, is there a way I can do this is my code when working with event handlers? Currently running like this:

  public void UpdateProgress(object sender, ProgressEventArgs e) { if (handler != null) { handler(sender, e); } } 
+4
source share
2 answers

Use AsyncOperationManager .

He will make a call for you. (internally, it uses a SynchronizationContext, as nobugz describes)

+3
source

You will need a reference to the client's Dispatcher object so that you can call Dispatcher.Invoke or Dispatcher.BeginInvoke to march the call into the client UI thread. Do this by letting the client provide you with the link that you need either through the constructor or using the property.

Another way to do this is to keep the reference to SynchronizationContext.Current in your class constructor. Use the send or send method. However, this requires the client to correctly initialize WPF (Application.Run should have been called) and build the class object from its user interface thread.

+3
source

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


All Articles