关于c#:异步委托调用和回调

Async Delegate invocation and callback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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。在这种情况下的最佳做法是什么。


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

像这样的东西:

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