C#异步调用方法
此类 unit
具有一个属性 bool status
,该属性标记是否应在该单元上调用方法 request
.我有另一个类,并且在其中有一个应调用 request
的方法.为了避免阻塞主线程,我想异步调用该方法.问题在于状态更改没有事件,并且我不想让异步调用执行类似以下的丑陋事情:
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);
或
while(!status){Thread.Sleep(100)}unit.request(args);
尤其是当我不知道状态
变为 true
的时间表时.
especially when I do not know the timescale in which status
turns true
.
我该怎么做?
更新:我忘了提到我不能更改 unit
.对此感到抱歉.
update: i forgot to mention that i cannot change unit
. sorry for that.
您想在属性更改时调用一个函数(无论是否异步).您有两种选择:
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.