Roelant M
Roelant M

Reputation: 1706

preferred way of synchronous code in async method

I've got a simple question, but i think there are multiple answers, but is there a good/bad practise about the following;

i'm working on the implementation for a given interface method:

Task<Model> GetDataAsync(CancellationToken token);

so in my implementation i get the following signature;

public async Task<Model> GetDataAsync(CancellationToken token)

however, this implementation lacks any async calls; just a regular: return x.firstOrDefault...

So i get the next problem; and here is some advice needed; should i do a await Task.Run(...); So i can still implement that given interface (that I need btw), or is there a better approach? and what are the benefits.

Upvotes: 3

Views: 311

Answers (1)

Severius5
Severius5

Reputation: 548

You can return completed task from given result without calling for await / Task.Run (considering you really dont want to run it from another thread)

public Task<Model> GetDataAsync(CancellationToken token)
{
    return Task.FromResult(x.FirstOrDefault(...));
}

and dont forget to remove async from method signature

Upvotes: 5

Related Questions