How is a sleeping thread until a callback for an asynchronous function is received?

I have a function that should only be executed when the callback is received from an asynchronous function.

how

I call the asynchronous function Stop() , and shortly after that I call the asynchronous function Start() .

The problem is called before Stop CallBack Start() is called, and therefore I get problems. Also I cannot separate the call of two functions. How can I not do this .:

 public void SomeFunction() { Stop(); } public void Stop_CallBack(eventargs e) { Start(); } 

I have to do it:

 public void SomeFunction() { Stop(); //Do something; Start(); } 

but before I get the stop call, my start () function is executed, creating problems for me.

Can someone help me how can I solve this problem.

+6
source share
2 answers

This is when you want to use wait descriptors. Here is a short code example to show one approach:

 class AsyncDemo { AutoResetEvent stopWaitHandle = new AutoResetEvent(false); public void SomeFunction() { Stop(); stopWaitHandle.WaitOne(); // wait for callback Start(); } private void Start() { // do something } private void Stop() { // This task simulates an asynchronous call that will invoke // Stop_Callback upon completion. In real code you will probably // have something like this instead: // // someObject.DoSomethingAsync("input", Stop_Callback); // new Task(() => { Thread.Sleep(500); Stop_Callback(); // invoke the callback }).Start(); } private void Stop_Callback() { // signal the wait handle stopWaitHandle.Set(); } } 
+18
source

Since they look like member functions, you can add an event member variable (either ManualResetEvent or AutoResetEvent ). Then, in the Stop() method, you set an event for signaling. Between the calls Stop (Stop)) and Start () you are waiting for an event.

 private AutoResetEvent _stopped = new AutoResetEvent(false); public void SomeFunction() { Stop(); _stopped.WaitOne(); Start(); } 

In the stop function you would do

 private void Stop() { try { // Your code that does something to stop } finally { _stopped.Set(); // This signals the event } } 

If using ManualResetEvent -

 private ManualResetEvent _stopped = new ManualResetEvent(false); public void SomeFunction() { Stop(); _stopped.WaitOne(); Start(); } private void Stop() { try { // Your code that does something to stop } finally { _stopped.Set(); // This signals the event } } private void Start() { _stopped.Reset(); // Your other start code here } 
+3
source

Source: https://habr.com/ru/post/890226/


All Articles