C # multithreading - GUI update using background events

I am new to C # and multithreading, so I apologize if this is a duplicate question, but as a newbie, it seems my question is a little different from the others I read.

My GUI works in one (main) thread. It invokes a background job (in the DLL, what I write too), which runs in a separate thread. The dll has no knowledge of the GUI (i.e., it cannot reference the GUI class).

Now, let's say I want to update the progress bar in the GUI based on the state of the dll thread -> What I do is create an event in the dll that every X percent will fire and the GUI will subscribe to this event. When an event is fired, the GUI will update the progress bar.

My questions:

  • Is the method of creating events the best way (given that the dll cannot refer to the GUI)?
  • How to ensure that my method above is "event safe"? Do I have to pass the percentage of progress in the event to be thread safe, or is there even more?
  • Do I need to use Invoke when updating the GUI? I saw a message that suggested that I did it, but I don’t understand why, because the panel is updated in the GUI thread ?!

I hope you can clarify this to me!

thank

+5
source share
6 answers

1.-I use this method all the time and yes, it will work

2.- int , . , , :

private void UpdatePercentage(int a)
{
    var myEvent = PercentageUpdatedEvent
    if(myEvent != null)
         myEvent(this, new ProgressBarEventArgs(a));
}

, , .

3. , Invoke, dll. BeginInvoke EndEnvoike, dll.

,

private myClass_OnPercentageUpdatedEvent(object a, ProgressBarEventArgs e)
{
    if(progressBar.InvokeRequired)
        progressBar.BeginInvoke((Action<object,ProgressBarEventArgs>)myCless_OnPercentageUpdatedEvent, a, e);
    else
    {
        progressBar.Value = e.Value;
    }
}
+3

, , , . .

, , , ; Delegate. ... , .

; , GUI .

+3

(3), Invoke. , .

0

, , .

delegate void UpdateDelegate(int val)
void Update(int val)
{
  if(this.InvokeRequired())
  {
     Invoke(new UpdateDeleage(Update),new object[] {val});
     return;
  }
  this.MyProgressBar.Value = val;
}

, . , , , . .

.

...

new Thread(()=>IncrementValues()).Start();

...

void IncrementValues()
{
   while(true)
   Update(new Random(0,10));
}
0

, / . , Task.

0

All Articles