异步委托调用和回调

本文关键字:回调 调用 异步 | 更新日期: 2023-09-27 18:35:39

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 调用,那么回调就不会命中。在这种情况下,最佳做法是什么。

异步委托调用和回调

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

像这样发短信:

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