Home > Enterprise >  Wait synchronously for a task to be completed in a not async method, but the task is WaitingForActiv
Wait synchronously for a task to be completed in a not async method, but the task is WaitingForActiv

Time:10-17

public void DoStuff()
{
    // I want to be able to call the method DoAsynckStuff and wait for the result.
    // I know that's not a usual thing to do
    // Usually also this will be async method and then just await the result.
    // I need this to be something like 
    var resultTask = DoAsynckStuff();
    resultTask.Wait();
    var result = resultTask.Result;
    //.....
}

public async Task<string> DoAsynckStuff()
{
    //...
}

Sorry, I'm new to async-await. What I need is that I want to wait for the result of a specific async method. I can't make the method async because it will cause some problems with the methods that will call that one.

I have tried the Wait method on the Task, just like on the code sample. But the task status will be always "waiting for activation".
I also tried to call the method resultTask.Start() before the wait method but that will throw

System.InvalidOperationException: Start may not be called on a promise-style task.

also result.RunSynchronously() will throw that exception.

I also viewed enter image description here

CodePudding user response:

It sounds like you're running your application with a synchronization context, like WinForms or WPF.

Anyway, the correct approach to run asynchronous code synchronously is to start a new thread and wait on it.

var result = Task.Run(() => DoAsyncStuff()).Result;
  • Related