c# - Which is the proper way for async method returns task? -


i confused following methods. 1 best , why? these working fine.

public string getstring(int i) {     return "testing number " + i.tostring(); }  //async methods i'm confused public task<string> getstringasync(int i) {     return task.fromresult<string>(getstring(i)); } //or public task<string> getstringasync(int i) {     task<string> task = new task<string>(() => getstring(i));     task.start();     return task; } //or public task<string> getstringasync(int i) {     var tcs = new taskcompletionsource<string>();     tcs.setresult(getstring(i));     return tcs.task; } 

the caller be

task<string> task = someclass.getstringasync(9); console.writeline(task.result); //or var result = await someclass.getstringasync(9); console.writeline(result); 

thank much.

i think may not understand why want use async. async .net allows freeing of threads waiting on external action take place (network call or hard disk call). windows uses i/o completion ports these calls , has added async/await keywords allow .net access native asynchronous calls. being said there little overhead when using async runtime has create state-machine keep track of threads current state before assigning await'd thread new task.

thus async tasks aren't using i/o completion port doing more harm good.

//async methods i'm confused public task<string> getstringasync(int i) {     return task.fromresult<string>(getstring(i)); } 

well let me correctly code async method:

//async methods i'm confused public asynctask<string> getstringasync(int i) {     return await task.fromresult<string>(getstring(i)); } 

still bad, because there no reason use async; unless i'm mistaken how task.fromresult() works, has additional overhead no benefit.

i'm going rewrite them async , give understanding of affect have.

public async task<string> getstringasync(int i) {     task<string> task = new task<string>(() => getstring(i));     await task.start();     return task; } 

it's extremely rare should creating , starting own tasks, it's not idea.

public task<string> getstringasync(int i) {     var tcs = new taskcompletionsource<string>();     tcs.setresult(getstring(i));     return tcs.task; } 

the taskcompletionsource designed wrap current asynchronous async/await pattern. since isn't wrapping type of asynchronous action there no performance benefit.

public string getstring(int i) {     return "testing number " + i.tostring(); } 

this best bet. don't use async/await unless actually need to.

stephen cleary has great set of posts talk tasks , async, highly recommend read through before diving async in .net.


Comments

Popular posts from this blog

unity3d - Rotate an object to face an opposite direction -

angular - Is it possible to get native element for formControl? -

javascript - Why jQuery Select box change event is now working? -