C#异步调用方法 [英] c# asynchronously call method

查看:118
本文介绍了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:

  1. 附加一个偶数,该偶数在属性更改时发出信号
  2. 定期检查属性的值

您不能做第一件事,所以您必须做第二件事.

You can't do the first, so you must do the second.

这篇关于C#异步调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆