Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my BeginInvoke method not async?

In order to avoid freezing of GUI, I wanted to run method connecting to DB asynchronously. Therefore I have written this:

DelegatLoginu dl = ConnectDB;

IAsyncResult ar = dl.BeginInvoke(null, null);

var result = (bool)dl.EndInvoke(ar);

But it is still freezing and I do not understand why. I thought BeginInvoke ensures the invoked code runs in another thread. Thank you!

like image 725
Petr Avatar asked May 05 '10 09:05

Petr


1 Answers

Calling EndInvoke() will block until the BeginInvoke() call has completed.

You need this kind of pattern in order for your long-running method to invoke a callback when it finishes:

public void DemoCallback()
{
    MethodDelegate dlgt = new MethodDelegate (this.LongRunningMethod) ;
    string s ;
    int iExecThread;

    // Create the callback delegate.
    AsyncCallback cb = new AsyncCallback(MyAsyncCallback);

    // Initiate the Asynchronous call passing in the callback delegate
    // and the delegate object used to initiate the call.
    IAsyncResult ar = dlgt.BeginInvoke(3000, out iExecThread, cb, dlgt); 
}

public void MyAsyncCallback(IAsyncResult ar)
{
    string s ;
    int iExecThread ;

    // Because you passed your original delegate in the asyncState parameter
    // of the Begin call, you can get it back here to complete the call.
    MethodDelegate dlgt = (MethodDelegate) ar.AsyncState;

    // Complete the call.
    s = dlgt.EndInvoke (out iExecThread, ar) ;

    MessageBox.Show (string.Format ("The delegate call returned the string:   \"{0}\", 
                                and the number {1}", s, iExecThread.ToString() ) );
}
like image 170
RickL Avatar answered Sep 28 '22 09:09

RickL