异步委托调用和回调

时间:2013-10-15 14:07:05

标签: c# asynchronous delegates

public delegate string AsyncMethodCaller(int callDuration, out int threadId);

class Program
{
    static void Main(string[] args)
    {
        int threadId;

        AsyncMethodCaller caller = new AsyncMethodCaller(TestMethod);

        IAsyncResult result = caller.BeginInvoke(3000,
            out threadId, new AsyncCallback(Callback), null);

        Console.WriteLine("Main thread {0} does some work.",
            Thread.CurrentThread.ManagedThreadId);

        string returnValue = caller.EndInvoke(out threadId, result);

        Console.WriteLine("The call executed on thread {0}, with return value \"{1}\".",
            threadId, returnValue);
    }

    static public string TestMethod(int callDuration, out int threadId)
    {
        Console.WriteLine("Test method begins.");
        Thread.Sleep(callDuration);
        threadId = Thread.CurrentThread.ManagedThreadId;
        return String.Format("My call time was {0}.", callDuration.ToString());
    }

    static void Callback(IAsyncResult result)
    {
        int a = 5;
        int b = 20;

        int c = a + b;

        Console.WriteLine(c + Environment.NewLine);
    }
}

此代码基本上是异步执行TestMethod。但我遇到的问题是在调用者调用EndInvoke之后,主线程停止并等待TestMethod完成作业。基本上整个应用程序都被卡住了。这个过程可以异步。 ?我的意思是我想要的是异步调用某个方法,然后等待回调,但是如果我删除了EndInvoke调用,那么CallBack就不会被命中。在这种情况下,最佳做法是什么。

1 个答案:

答案 0 :(得分:0)

您最好使用Tasks及其Task.Wait方法。 http://msdn.microsoft.com/ru-ru/library/dd321424.aspx

像这样:

var returnValue = Task<string>.Factory.StartNew(() => TestMethod());