我有异步回调,它被传递给Timer(来自System.Threading)构造函数:
private async Task HandleTimerCallback(object state)
{
if (timer == null) return;
if (asynTaskCallback != null)
{
await HandleAsyncTaskTimerCallback(state);
}
else
{
HandleSyncTimerCallback(state);
}
}
和计时器:
timer = new Timer(async o => await HandleTimerCallback(o), state, CommonConstants.InfiniteTimespan,
CommonConstants.InfiniteTimespan);
有没有办法在lambda中省略o
param?非同步的原因我可以将handler
作为代理传递
timer = new Timer(HandleTimerCallback, state, CommonConstants.InfiniteTimespan,
CommonConstants.InfiniteTimespan);
答案 0 :(得分:22)
有没有办法在lambda中省略那个o param?
当然,只需将您的事件处理程序方法定义为async void
:
private async void HandleTimerCallback(object state)
答案 1 :(得分:1)
您可以使用David Fowler here建议的包装方法:
public class Pinger
{
private readonly Timer _timer;
private readonly HttpClient _client;
public Pinger(HttpClient client)
{
_client = client;
_timer = new Timer(Heartbeat, null, 1000, 1000);
}
public void Heartbeat(object state)
{
// Discard the result
_ = DoAsyncPing();
}
private async Task DoAsyncPing()
{
await _client.GetAsync("http://mybackend/api/ping");
}
}
答案 2 :(得分:-2)
我使用了上面建议的 Vlad 之类的包装器,然后使用了 Task.Wait 以便异步过程完成:
private void ProcessWork(object state)
{
Task.WaitAll(ProcessScheduledWorkAsync());
}
protected async Task ProcessWorkAsync()
{
}