Quantcast
Viewing latest article 3
Browse Latest Browse All 19

async / await / task

OK, but what is the best way?

     - Task.WaitAll -> is clear I understand.

     - ManualResetEvent

     - await

     - AutoResetEvent

Can you show that for the variants? name the advantages anddisadvantages?

     

Thanks in advance.

 

Best regards Markus

Take the example of AutoResetEvent:

class Program { static AutoResetEvent autoResetEvent = new AutoResetEvent(false); static string dataFromServer = ""; static void Main(string[] args) { Task task = Task.Factory.StartNew(() => { GetDataFromServer(); }); //Put the current thread into waiting state until it receives the signal autoResetEvent.WaitOne(); //Thread got the signal Console.WriteLine(dataFromServer); } static void GetDataFromServer() { //Calling any webservice to get data Thread.Sleep(TimeSpan.FromSeconds(4)); dataFromServer = "Webservice data";

autoResetEvent.Set(); } }

Notice that the last statement——This will automatically set the state of AutoResetEvent's state to false, so that you can reuse the class instance by calling "WaitOne()" again in somewhere else. However, if you use ManualResetEvent, you MUST ADD"manualResetEvent.Reset()" at the back of:

autoResetEvent.WaitOne();

Because ManualResetEvent WON'T set the state to false, which means for ManulResetEvent,

you have to set the state by calling "Reset()" manually.


Reproduce your quesions with ScreenToGif is your choice. 
For IIS: IIS Forum
For WebSite of .NET: ASP.NET Forum
For others: StackExchange
For spam-sender or forum urgent issues, Send your Email at:  forumsfeedback@microsoft.com


Viewing latest article 3
Browse Latest Browse All 19

Trending Articles