非淡泊无以明志,非宁静无以致远 -心静如止水,动于静

異步調用

我們知道可以用control.beginInvoke() 和 control.EndInvoke()來進行異步調用,但endInvoke()是block的,如果在調用者函數體內執行還是達不到真正的異步,今天在網上看到一篇可以做到真正異步,在調用都函數體內調用control.BeginInvoke(),然后傳遞一個callback函數指針,在被調用者函數體內調用EndInvoke()并激活調用者傳進來的callback,以便通知調用者執行結果
Linkage為http://www.codeproject.com/csharp/AsyncMethodInvocation.asp

<PRE lang=cs id=pre19 style="MARGIN-TOP: 0px">private void CallFooWithOutAndRefParametersWithCallback()
{
    // create the paramets to pass to the function
    string strParam1 = "Param1";
    int intValue = 100;
    ArrayList list = new ArrayList();
    list.Add("Item1");

    // create the delegate
    DelegateWithOutAndRefParameters delFoo =
        new DelegateWithOutAndRefParameters(FooWithOutAndRefParameters);

    delFoo.BeginInvoke(strParam1,
        out intValue,
        ref list,
        new AsyncCallback(CallBack), // callback delegate!
        null);
}

private void CallBack(IAsyncResult ar)
{
    // define the output parameter
    int intOutputValue;
    ArrayList list = null;

    // first case IAsyncResult to an AsyncResult object, so we can get the
    // delegate that was used to call the function.
    AsyncResult result = (AsyncResult)ar;

    // grab the delegate
    DelegateWithOutAndRefParameters del =
        (DelegateWithOutAndRefParameters) result.AsyncDelegate;

    // now that we have the delegate,
    // we must call EndInvoke on it, so we can get all
    // the information about our method call.

    string strReturnValue = del.EndInvoke(out intOutputValue,
        ref list, ar);
}</PRE>

posted @ 2007-10-31 17:15  烟雨客  阅读(238)  评论(0编辑  收藏  举报