简体   繁体   中英

Code after 'await Task.Delay(5000)' is not executing until the execution of relaycommand is completed

In my WPF application, i am calling relaycommand

    private void AutoRun(object parameter)
    {
        for(int i=0;i<10;i++)
        {
        MoveLotCommand.Execute(0);

        }

    }

which inturns call another relay command

  private void MoveLot(object parameter)
    {
        //Some Code

            var Task = StartLotProcessing(currentAssemblyPlant);

        }
    }

and this relay command will call another async function

    async Task StartLotProcessing(int currentAssemblyPlant)
    {
        await Task.Delay(5000);
        var nextAssemblyPlant = currentAssemblyPlant + 1;

        //Process after await
    }

The issue is, my code after 'await Task.Delay(5000)' does not executes until my AutoRun() function execution is completed.

I am trying to execute the await async code for each variable in my for loop.

Any help would be appreciated and sorry for my explanation.

You are not calling the method correctly : you are missing the await operator to indicate that you have to wait, otherwise you effectively schedule the task but do not wait for it. The task is scheduled in a synchronous fashion, hence when your method returns.

Change your call to this, and the issue should go away:

await StartLotProcessing(currentAssemblyPlant);

The problem appears to be that you are calling StartLotProcessing asynchronously but not waiting for the task to complete before moving on.

Ideally you would call use async/await the whole way up the stack:

await MoveLotCommand.Execute(0);
...
await StartLotProcessing(currentAssemblyPlant);

If you're unable to do that, then you should call

var task = StartLotProcessing(currentAssemblyPlant);
...
task.Wait();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM