c# - Task return value, without Task<T> (async/await pattern) -


i write following:

public string getsomevalue() {     //directly return value of method 'dosomeheavywork'...     var t = dosomeheavywork();     return t.result; }  public task<string> dosomeheavywork() {     return task.run(() => {         // long working progress , return string         return "hello world!";     }); } 

as can see return result dosomeheavywork() have used task.result property, works okay, according researches block thread.

i use async/await pattern cant seem find how this. if did same async/await current knowledge end this:

public async task<string> getsomevalue() {     //directly return value of method 'dosomeheavywork'...     var t = dosomeheavywork();     return await t; }  public task<string> dosomeheavywork() {     return task.run(() => {         // long working progress , return string         return "hello world!";     }); } 

this solution doesnt quite fit needs because want return string , not task<string>, how can achieved async/await?

you can't.

the entire point of async run code asynchronously. code returns promise of future string value, represented in .net task<string>.

think way: if code calls public string getsomevalue(), time method returns, already have string. synchronous, definition.

in example, have "heavy" work interpret mean "cpu-bound". in case, work synchronously:

public string dosomeheavywork() {   // long working progress , return string   return "hello world!"; } 

in general, apis should not "lie"; if synchronous, should have synchronous (non-task-returning) signature.

edit: per comment, "heavy" work wcf call, i/o-bound, not cpu-bound.

in case, work naturally asynchronous. use asynchronous wcf methods (not task.run), , allow asynchrony grow through codebase:

public async task<string> getsomevalueasync() {   //directly return value of method 'dosomeheavywork'...   var t = dosomeheavyworkasync();   return await t; }  public async task<string> dosomeheavyworkasync() {   // call asynchronous wcf client.   await ...;   return "hello world!"; } 

Comments

Popular posts from this blog

how to proxy from https to http with lighttpd -

android - Automated my builds -

python - Flask migration error -