我有一些异步方法:
// not ideal
private TaskCompletionSource<A> _tcsA;
private TaskCompletionSource<A> _tcsB;
private TaskCompletionSource<A> _tcsC;
...
public Task<A> GetAAsync() {
_currentTask = TaskType.A;
_tcsA = new TaskCompletionSource<A>();
// some complex non-sync task, using http/events that ends with Complete();
// QueueRequest?.Invoke(this, taskInfo); // raise request -- this does not return
return _tcsA.Task;
}
public Task<B> GetBAsync() {
_currentTask = TaskType.B;
_tcsB = new TaskCompletionSource<B>();
// some complex non-sync task, using http/events that ends with Complete();
// QueueRequest?.Invoke(this, taskInfo); // raise request -- this does not return
return _tcsB.Task;
}
public Task<C> GetCAsync() {
_currentTask = TaskType.C;
_tcsC = new TaskCompletionSource<C>();
// some complex non-sync task, using http/events that ends with Complete();
// QueueRequest?.Invoke(this, taskInfo); // raise request -- this does not return
return _tcsC.Task;
}
// called by an external source, a http listener / processor
// this should complete the async call by the client and return results
public void Complete(Result result) {
switch (_currentTask) {
case TaskType.A:
_tcsA.SetResult(new A());
break;
case TaskType.B:
_tcsB.SetResult(new B());
break;
case TaskType.C:
_tcsC.SetResult(new C());
break;
}
_currentTask = TaskType.None;
}
为简单起见,以上是半伪代码。我这样称呼其中一种方法:
A a = await service.GetAAsync();
现在的问题是TaskCompletionSource<T>
通用的,如果我有 100 种方法,我将不得不为每个返回类型创建一个变量。但是由于一次只能调用一个方法,因此最好使用单个方法TaskCompletionSource
,但不要将其键入到object (TaskCompletionSource<object>)
.
我不想这样做:
object a = await service.GetAAsync();
因为这需要客户进行铸造。所以最好的解决方案是有一个单一的TaskCompletionSource
,但以某种方式输入。或者可以有一个字典TaskCompletionSource
。这两者在我看来都是不可能的。
我应该如何解决这个问题?
更新:
有关我的情况的背景,请查看:Wrap synchronous code into async await in disconnected scenario