0
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 不会被命中。在这种情况下,最佳做法是什么。

4

1 回答 1

0

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

像这样的东西:

var returnValue = Task<string>.Factory.StartNew(() => TestMethod());
于 2013-10-15T14:35:53.473 回答