This question has already been answered:

There is a class with a cycle in a separate thread. There is an EventHandler and a subscription to it in another class. How from a loop in another thread is it safe to create an event? When you try to create it and, for example, create an entry in the textbox, an exception automatically flies with a message attempting access from another thread.

Excerpts from the code:

  1. public event EventHandler<NewDataEventArgs> NewData; - event announcement
  2. NewData(this, e); - call event in the stream

Reported as a duplicate by the participants andreycha , Pavel Mayorov , pavel , dirkgntly , user207618 Aug 28 '16 at 6:43 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

Since the event handler is called on the thread in which the event was triggered, you get the situation that you are trying to access a элементу управления from another thread (other than UI) - but you cannot do that.

In order to get around this, there are several options; here are some of them:

Option 1

You can use SynchronizationContext

1) We get the SynchronizationContext , it is important to get it for the UI, therefore somewhere in the CodeBehind form we write:

 _context = SynchronizationContext.Current; 

2) Next in your event handler, which is triggered by NewData(this, e); it is necessary to use the received synchronization context in order to safely access the UI element

 _context?.Post(s => { // Здесь пишите код, который получает доступ к контролу }, null); 

Option 2

In the event handler that is triggered by NewData(this, e); you can call your control and call the Invoke method in the case of WinForms

 myControl.Invoke(myDelegate); 

or use Dispatcher.BeginInvoke in case of WPF

  Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate() { // Здесь пишите код, который получает доступ к контролу }