0

我有一个场景,我必须在学生列表中并行/独立地运行学生列表。但是,当我用下面的代码运行这些程序时,程序没有正确完成就结束了。C#等待进程毫无例外地退出

public async Task ProcessStudents() 
{ 
    var students = await GetStudentsAsync().ConfigureAwait(false); 
    ProcessSingleStudent(students); 
} 

private static ProcessSingleStudent(IEnumerable<StudentModel> students) 
{ 
    students.ForEach(async student => 
    { 
     await ValidateSingleStudentAsync(student).ConfigureAwait(false); 
    } 
} 

private async Task ValidateSingleStudentAsync(StudentModel student) 
{ 
    //Do some validations here 
    if(validate) 
    { 
     var updated = await UpdateStudentAsync(student).configureAwait(false); //<== This cause issue 
    } 
} 

当我看到UpdateStudentAsync造成的问题,如果有F10去这个方法不返回任何东西,控制台应用程序停止。即使我把每个电话都拨打try-catch我什么都找不到。如果我进入每个调试点,我会得到预期的结果。

无法理解问题出在哪里。

+0

哪里是'UpdateStudentAsync'的代码? –

+0

请分享调用'ValidateSingleStudentAsync'的代码,并给我们提供关于主应用程序的更多信息,这意味着:如果'ValidateSingleStudentAsync'运行在临时上下文中,则运行在Windows Form App或Console App上 –

+0

This是你需要的https://stackoverflow.com/a/39174582/782754 –

回答

1

您的ProcessSingleStudent不会等待每个调用的结果。因此,迭代

后终止你想是这样的:https://stackoverflow.com/a/15136833/8302901

+0

你是对的,而不是在foreach中运行异步方法,我将返回的任务添加到任务列表中,然后将该任务列表传递给Task.WhenAll ()' – Kenz

0

记住,异步的await是会传染或ProcessSingleStudent方法本身不是异步,它是同步的。你需要的是像

private async Task ProcessSingleStudent(IEnumerable<StudentModel> students) 
{ 
    await students.ForEach(async student => 
    { 
     await ValidateSingleStudentAsync(student).ConfigureAwait(false); 
    }).ConfigureAwait(false) 
} 

但是这是不可能的(它不会编译)不具名AsyncEnumerator库的一点点帮助。

代码变得

private async Task ProcessSingleStudent(IEnumerable<StudentModel> students) 
    { 
     await students.ParallelForEachAsync(async student => 
     { 
      await ValidateSingleStudentAsync(student).ConfigureAwait(false); 
     }, 
     maxDegreeOfParalellism: 30, 
     cancellationToken: null, 
     breakLoopOnException: true 
     ).ConfigureAwait(false) 
    } 
+0

我不认为第一个代码块可以在ForEach方法中添加await。 – Kenz

+0

不是,我说过。也许我没有说清楚。 –