【发布时间】:2016-09-23 18:00:30
【问题描述】:
我已经实现了一个基于 Timer 的 polling-worker。例如,您可以在客户端考虑TryConnect——我调用TryConnect,它最终会在一段时间内连接。它处理多个线程,如果连接已经在进程中,所有后续TryConnect 立即返回,无需任何额外操作。在内部,我只是创建一个计时器,并每隔一段时间尝试连接——如果连接失败,我会再试一次。以此类推。
小缺点是它是“fire&forget”模式,现在我想将它与“async/await”模式结合起来,即改为调用:
client.TryConnect(); // returns immediately
// cannot tell if I am connected at this point
我想这样称呼它:
await client.TryConnect();
// I am connected for sure
如何更改我的实现以支持“async/await”?我正在考虑创建空的Task(仅用于await),然后用FromResult 完成它,但是这个方法创建一个新任务,它没有完成给定的实例。
为了记录,当前的实现看起来像这样(只是代码的草图):
public void TryConnect()
{
if (this.timer!=null)
{
this.timer = new Timer(_ => tryConnect(),null,-1,-1);
this.timer.Change(0,-1);
}
}
private void tryConnect()
{
if (/*connection failed*/)
this.timer.Change(interval,-1);
else
this.timer = null;
}
【问题讨论】:
标签: c# timer async-await polling