Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Delegates in C# Asynchronously

I have the following delegate

delegate void UpdateFileDelegate(long maxFileID);

That I am calling from a WinForms app like so

UpdateFileDelegate FD = new UpdateFileDelegate(ClassInstance.UpdateFile);
FD.BeginInvoke(longIDNumber,null,null);

It runs asynchronously but the question I have is how can I tell when the Method is done executing so I can let the end user know?

Update: Thanks to the recommendations below the following code does the trick. Also this article was helpful in getting me to understand what my code is actually doing.

delegate void UpdateFileDelegate(long maxFileID);
UpdateFileDelegate FB = new UpdateFileDelegate(ClassInstance.UpdateFile);
AsyncCallback callback = new AsyncCallback(this.CallBackMethod);
IAsyncResult result = FB.BeginInvoke(longIDNumber);

private void CallBackMethod(IAsyncResult result)
    {
     AsyncResult delegateResult = (AsyncResult)result;

     UpdateFileDelegate fd = (UpdateFileDelegate)delegateResult.AsyncDelegate;
     fd.EndInvoke(result);
     MessageBox.Show("All Done!");
    }
like image 248
etoisarobot Avatar asked Nov 17 '25 20:11

etoisarobot


1 Answers

See Calling Synchronous Methods Asynchronously

The BeginInvoke will return an IAsyncResult, which enables a number of different ways to be aware of when it is done, such as using its AsyncWaitHandle.WaitOne() method. It depends on what you are doing in the meantime.

Or you can pass a delegate for a callback method to BeginInvoke. This is arguably the most powerful strategy, but sometimes is overkill.

like image 88
Dave Mateer Avatar answered Nov 20 '25 10:11

Dave Mateer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!