Home > OS >  C# don't wait task to finish, but result needed
C# don't wait task to finish, but result needed

Time:02-06

Simply I want to make an external call to external api which has SenMessageAsync(string message) method and i need to return my client Ok() without waiting it to finish. But on the backend side I need to response of SendMessageAsync() method for continue some process. I mean somehow I need to await it.

Example

try
{
    //...
    var response = await SendMessageAsync("test"); //dont wait the response, return Ok()
    //do something with response
}
catch(MyException ex)
{
    //Log
}
catch(Exception ex)
{
    //Log
}

CodePudding user response:

You can use the Task.Run method to run the SendMessageAsync method asynchronously on a separate thread. You can then return Ok() to the client immediately, while the SendMessageAsync method continues to run in the background. To wait for the result of the SendMessageAsync method, you can use the await keyword within the Task.Run method.

Here's an example:

public async Task<IActionResult> MyAction()
{
    // Return Ok() immediately to the client
    _ = Task.Run(async () => 
    {
        // Run SendMessageAsync asynchronously on a separate thread
        var result = await SendMessageAsync("My message");
        // Continue processing using the result of SendMessageAsync
        // ...
    });

    return Ok();
}

CodePudding user response:

try
{
    DisplayLater();
    Console.WriteLine("Return Ok");
}
finally
{
    Console.Read();
}

static async Task DisplayLater()
{
    await Task.Delay(2000);
    Console.WriteLine("Show message after 2 seconds.");
}

enter image description here

  • Related