为什么我的BeginInvoke方法不是异步的?

Pet*_*etr 8 c# multithreading begininvoke

为了避免冻结GUI,我想运行异步连接到DB的方法.所以我写了这个:

DelegatLoginu dl = ConnectDB;

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

var result = (bool)dl.EndInvoke(ar);
Run Code Online (Sandbox Code Playgroud)

但它仍然冻结,我不明白为什么.我认为BeginInvoke确保调用的代码在另一个线程中运行.谢谢!

Ric*_*ckL 12

调用EndInvoke()将阻塞,直到BeginInvoke()调用完成.

您需要这种模式,以便您的长时间运行方法在完成时调用回调:

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() ) );
}
Run Code Online (Sandbox Code Playgroud)


Chr*_*ich 5

请参阅EndInvoke 此处的说明,具体如下:

EndInvoke()函数用于检索异步调用的结果.它可以在BeginInvoke()之后的任何时候调用.如果异步调用尚未完成,则EndInvoke()将阻塞直到完成.