如何异步运行

时间:2013-02-06 11:08:35

标签: c# multithreading async-await

我必须加载两个并行的大文件 到目前为止我有这个代码

以下代码是点击按钮方法

private async void MILoadLogFile_Click(object sender, RoutedEventArgs e) 
{       
    ...
    if (oFD.ShowDialog() == true)
    {
        await myLogSession.LoadCompassLogAsync(oFD.FileName);
        await myLogSession.LoadCoreServiceLogAsync(oFD.FileName);
    }
}

加载方法:

public async Task LoadCompassLogAsync(String fileName)
{
    StreamReader streamReader = new StreamReader(fileName);
    if (fileName.Contains("Compass"))
    {
        ...
        try
        {
            using (streamReader)
            {
                //Console.Out.WriteLine("lineCount: " + lineCount);
                while (((line = await streamReader.ReadLineAsync()) != null)
                       && !CompassLogLoadCompleted)
                {
                    ...
                    loggingLvl = new LoggingLvl(eLoggingLvl);
                    CompassLogData cLD = new CompassLogData(id, dateTime, loggingLvl, threadId, loggingMessage);

                    await addRoCompassLogCollectionAsync(cLD);
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

LoadCoreServiceLogAsync几乎与LoadCompassLogAsync相同。

两种加载方法按顺序运行。我希望它们并行运行。

1 个答案:

答案 0 :(得分:1)

您的代码将在另一个之后运行一个任务。要并行运行这两个任务,您可以使用Task.WaitAll方法:

var loadCompassLogTask = myLogSession.LoadCompassLogAsync(oFD.FileName);
var loadCoreServiceLogTask = myLogSession.LoadCoreServiceLogAsync(oFD.FileName);
Task.WaitAll(loadCompassLogTask, loadCoreServiceLogTask);

或者如果您想使用await,可以使用Task.WhenAll

var loadCompassLogTask = myLogSession.LoadCompassLogAsync(oFD.FileName);
var loadCoreServiceLogTask = myLogSession.LoadCoreServiceLogAsync(oFD.FileName);
await Task.WhenAll(loadCompassLogTask, loadCoreServiceLogTask);