这是我的方法。我有几个IEventProviders
,
interface IEventProvider
{
Task<Event> GetEvent();
}
然后我得到一个容器类来包装它们,并继续调用并等待GetEvent()
等待下一个事件,例如套接字异步接收、计时器滴答等。
class EventProviderContainer : IEventProvider
{
private IEventProvider[] _providers;
private Task<Event>[] _tasks;
public EventProviderContainer(params IEventProvider[] providers)
{
_providers = providers;
}
public async Task<Event> GetEvent()
{
// Fill the _tasks first time we call the method.
if (_tasks == null)
_tasks = (from p in _providers select p.GetEvent()).ToArray();
Task<Event> task = await Task<Event>.WhenAny(_tasks);
// Get the provider index whose previous task is done.
int index = Array.IndexOf(_tasks, task);
// put next event of the provider into array.
_tasks[index] = _providers[index].GetEvent();
return await task;
}
}
我觉得有点丑。这是更好的方法吗?