-1

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

下面的代码是点击按钮方法

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

两种加载方法依次运行。我希望它们并行运行。

4

1 回答 1

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);
于 2013-02-06T11:16:08.577 回答