This question has already been answered:

Good day. I make an important element in the stream. I start a stream from the main. And when the stream is executed, the studio swears not on the action, but on the condition (wtf ????) enter image description here

Reported as a duplicate by PashaPash members , ArchDemon , ixSci , Vesper , aleksandr barakin Jul 22 '15 at 15:01 .

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 .

  • one
    the studio swears by the action - by reading the Value property. Use Invoke or async. - PashaPash

2 answers 2

Write a small auxiliary class:

public static class WinFormsSafeCallHelper { public static T SafeGetValue<T>(this Control control, Func<T> func) { if (control.InvokeRequired) { return (T)control.Invoke(func); } return func(); } } 

Now your condition can be rewritten as:

 if (trackBar1.SafeGetValue(() => trackBar1.Value >= 20)) { // do something } 

    A studio complains not about a condition, but about a call to an element created in another thread. Read about delegates . You can remove the check for this error, but I do not advise you. Sometimes it happens ...

    • The problem is that I can fix such errors with the "if (control.InvokeRequired)" method. But how to fix this error in the body if? I would be very happy if they showed me the code where Invoke is used in the if body. - JamesJGoodwin