There is this class unit
that has a property bool status
that marks whether a method, request
, should be called on the unit. I have my other class, and in it, there is a method that should call request
. To avoid blocking the main thread, I want to call the method asynchronously. The problem is that there isn't an event for the status change, and I don't want to make my asynchronous call do ugly stuff like:
while(!status){}unit.request(args);
or
while(!status){Thread.Sleep(100)}unit.request(args);
especially when I do not know the timescale in which status
turns true
.
How do I do this?
update: i forgot to mention that i cannot change unit
. sorry for that.
This is the classic polling problem, and there really isn't an elegant solution when polling is concerned. But we can work some functional programming in to get something which isn't a nightmare to use.
Example:
This is a sample of how you can manage this using an event.
Suppose this is your class
Here is how you can use it
This outputs
Use a
System.Threading.AutoResetEvent
instead of abool
if possible:In your asynchronous method, wait for it:
Then, to signal it in your other class, call
Set
:You want to call a function (be it asynchronously or not) when a property changes. You have two choices:
You can't do the first, so you must do the second.