The return value of the task, without Task <T> (async / await template)
I would like to write the following:
public string GetSomeValue() { //directly return the value of the Method 'DoSomeHeavyWork'... var t = DoSomeHeavyWork(); return t.Result; } public Task<string> DoSomeHeavyWork() { return Task.Run(() => { // do some long working progress and return a string return "Hello World!"; }); } As you can see, to return the result from DoSomeHeavyWork() , I used the Task.Result property, which works fine, but according to research, this will block Thread.
I would like to use the async / await template for this, but cannot find how to do this. If I did the same with async / await with my current knowledge, I always get the following:
public async Task<string> GetSomeValue() { //directly return the value of the Method 'DoSomeHeavyWork'... var t = DoSomeHeavyWork(); return await t; } public Task<string> DoSomeHeavyWork() { return Task.Run(() => { // do some long working progress and return a string return "Hello World!"; }); } This solution does not meet my needs, because I want to return ONLY a string, not Task<string> , how can this be achieved with async / wait?
You can not.
The whole point of async is to run asynchronous code. Thus, the code returns a promise of the future string value, presented in .NET as Task<string> .
Think of it this way: if your code calls public string GetSomeValue() , then by the time the method returns, you already have a string . This is synchronous, by definition.
In your example, you have "hard" work, which I interpret as "CPU bound." In this case, just do the job synchronously:
public string DoSomeHeavyWork() { // do some long working progress and return a string return "Hello World!"; } In general, APIs should not βlieβ; if they are synchronous, then they must have a synchronous signature (not Task substitution).
Edit: According to your comment, βhardβ work is a WCF call that is related to I / O, not CPU binding.
In this case, the operation is naturally asynchronous. Use asynchronous WCF methods (not Task.Run ) and let asynchrony grow through your code base:
public async Task<string> GetSomeValueAsync() { //directly return the value of the Method 'DoSomeHeavyWork'... var t = DoSomeHeavyWorkAsync(); return await t; } public async Task<string> DoSomeHeavyWorkAsync() { // Call asynchronous WCF client. await ...; return "Hello World!"; }