bui*_*ete 1 c# asynchronous async-await
in the following snippet
private async void FinishCommandExecute()
{
Console.WriteLine("FinishCommandExecute_1");
_granularBlobAnalyzer.SaveResult(SampleID, Operator, Comments);
Console.WriteLine("FinishCommandExecute_2");
await Task.Run(() => FlushCommandExecute());
Console.WriteLine("FinishCommandExecute_3");
State = GBAState.IDLE;
Console.WriteLine("FinishCommandExecute_4");
}
private async void FlushCommandExecute()
{
Console.WriteLine("FlushCommandExecute_1");
State = GBAState.FLUSHING;
Console.WriteLine("FlushCommandExecute_2");
await Task.Run(() => _granularBlobAnalyzer.Flush()); // Task to wrap sync method
Console.WriteLine("FlushCommandExecute_3");
State = GBAState.STOPPED;
Console.WriteLine("FlushCommandExecute_4");
}
Run Code Online (Sandbox Code Playgroud)
I call FinishCommandExecute (it is bound to a button as command), and I would expect the finish command would call the flush command and wait for it to finish, but it doesn't wait past the await inside the flush command...and the execution continues
if you look at the comment, I would expect the following in the console
while the actual is:
why doesnt async wait for the task run in the second async method
FlushCommandExecute
is an async void, so it runs unobserved, you cant await\wait for it unless you use some sort of synchronisations mechanism like a AutoResetEvent
ect or refactor your code to call async Task
and await that.
private async void FlushCommandExecute() => await FlushCommand();
private async void FinishCommandExecute()
{
...
await FlushCommand();
...
}
private async Task FlushCommand()
{
...
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53 次 |
最近记录: |