Home > Net >  Async function in another window
Async function in another window

Time:06-10

I'm having issues with running a function as async. I'm trying to make an async call to set up some timmers to run some code. I've tried making the function async and I feel like I'm doing something wrong. I've narrowed down the functionality to two functions and added a 20-second sleep in the function to test out the issue and I'm wondering if my sleep is pausing the whole application or am I doing async incorrectly? Any point in the right direction would be helpful. Thank you in advance.

private async void RunAsyncExample(){
    Task timersTask = mainWindow.StartTimers();   //This has a 20 sec sleep
    mainWindow.PullReceipt(handoff);              //This should not wait
    await timersTask;                             //This should wait
}

Below is the mainWindow.StartTimers

public async Task<Task> StartTimers()
{
    _log.LogError("starting timer");
    System.Threading.Thread.Sleep(20000);
    _log.LogError("ending timer");
    return Task.CompletedTask;
}

CodePudding user response:

Try the following:

public async Task StartTimers()
{
    _log.LogError("starting timer");
    await Task.Delay(20000);
    _log.LogError("ending timer");
}

Incidentally, your code has many issues:

  • You should not declare an async method if it doesn't await
  • You should not Sleep
  • You should put non UI code outside UI
  • You should name methods properly. StartTimers doesn't start any timer, so it is not an appropriate name.
  • async void is appropriate only for asynchronous event handlers
  • Related