Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Async await method gets stuck

I have an API method with this signature:

public Task<MResponse> StartAsync(MRequest request)

I can’t change that (I can change the implementation inside but not the signature of the method).

This is how I call this method:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var ret = await _SyncClient.StartAsync(Request);

This is the implementation

  public Task<MResponse> StartAsync(MRequest request)
  {
       if (request.Number == 1)
       {
            return new Task<MResponse>(() => new MResponse() { Description = "Error", Code = 1 });
       }
       else
       {
            return new Task<MResponse>(() => new MResponse() { Description = "", Code = 0 });
       }
   }

On the debug mode I see that my code get into StartAsync and and the return and finish it, but its look like the wait never ends….

I have no idea what it can be.

If you need more information about my code, let me know.

>Solution :

It looks like you’re not actually having anything asynchronous to do in the implementation. That’s fine, there’s always cases where the signature is set (i.e. an interface) and some implementations don’t need it.

You can still make the method async and just return the response as if it were as synchronous method, like so:

public async Task<MResponse> StartAsync(MRequest request)
{
    return new MResponse() { ... }
}

But that will probably trigger Intellisense to tell you there’s nothing being awaited in your method. A better approach is to use Task.FromResult like so:

public Task<MResponse> StartAsync(MRequest request)
{
    return Task.FromResult(new MResponse() ... );
}

which will return a Task that already as completed and therefore will not block your await in the follow-up.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading