与Asyn循环并等待

时间:2016-03-13 02:19:14

标签: c# multithreading

如何并行执行以下循环。我做错了什么导致循环按顺序执行。

class Program
{
    static void Main(string[] args)
    {
        AsynWaitTest _asynWaitTest;

        _asynWaitTest = new AsynWaitTest();
        _asynWaitTest.CallAsynWaitTest();
        Console.ReadLine();
    }
}

public class AsynWaitTest
{
    public void CallAsynWaitTest()
    {
        CallLongRunningMethod();
    }

    private async void CallLongRunningMethod()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Loop Value : {0}", i.ToString());
            string result = await LongRunningMethodAsync(i.ToString());
            Console.WriteLine("Loop Value : {0}", result);
        }

    }

    private async  Task<string> LongRunningMethodAsync(string message)
    {
        return await Task.Run<string>(() => LongRunningMethod(message));
    }

    private string LongRunningMethod(string message)
    {
        Thread.Sleep(2000);
        return "Hello " + message;
    }

}

0 个答案:

没有答案