C # stop and continue

I need to make a way efficiently in C #:

Make program execution stopped until a specific value is changed.

Note: I do not want to do this with a while loop to avoid CPU loss.

Edit: And I want him to respond as quickly as after changing the value.

Edit:. It will be inside my class method, which is called by other code, however, the value to be checked is inside my class ... It is assumed that the method should wait for others to evaluate the code and change my value .. then it should continue to execute its work. Unfortunately, this is done many times (so I need to care about performance)

+6
c #
source share
5 answers
+15
source share

If the value you expect is set somewhere in another application, you can use the wait descriptor:

AutoResetEvent waitHandle = new AutoResetEvent(); ... //thread will sleep here until waitHandle.Set is called waitHandle.WaitOne(); ... //this is where the value is set someVar = someValue; waitHandle.Set(); 

(note that WaitOne and Set must occur in separate threads, since WaitOne blocks the thread on which it is called)

If you don’t have access to code that changes the value, the best way to do it, as others say, is to use a loop to check if the value has changed and use Thread.Sleep () so that you don’t use as much processor time:

 while(!valueIsSet) { Thread.Sleep(100); } 
+7
source share
 while(some-condition-here) { Thread.CurrentThread.Sleep(100); // Release CPU for 100ms } 

He called spin-sleep, I think. Of course, you can set 100 to whatever you want. This is basically a timeout for each check.

There are other ways to do this, but it is the easiest and most effective.

In this e-book he is really mentioned:

Threading in C # by Joseph Albahari: Part 2: Basic Sync

+6
source share

You can use the Observer design pattern. It is designed to solve problems like yours.

This template mainly contains a theme and an observer. You can make him react to any changes very quickly.

You can find more information and sample code here.

+3
source share
+2
source share

All Articles