非通用TaskCompletionSource或替代 [英] Non-Generic TaskCompletionSource or alternative
问题描述
我正与一个警告窗口(WPF的Telerik),它通常异步显示(code继续运行时,它是开放的),我希望把它同步使用异步/等待。
I'm working with an alert window (Telerik WPF) that is normally displayed asynchronously ( code continues running while it is open) and I want to make it synchronous by using async/await.
我有这个与 TaskCompletionSource
工作,但这个类是通用的,返回一个对象如任务<布尔>
时,所有我想要的是一个普通的工作
没有返回值。
I have this working with TaskCompletionSource
but that class is generic and returns an object like Task<bool>
when all I want is a plain Task
with no return value.
public Task<bool> ShowAlert(object message, string windowTitle)
{
var dialogParameters = new DialogParameters { Content = message };
var tcs = new TaskCompletionSource<bool>();
dialogParameters.Closed += (s, e) => tcs.TrySetResult(true);
RadWindow.Alert(dialogParameters);
return tcs.Task;
}
在code调用该方法
The code that calls that method is
await MessageBoxService.ShowAlert("The alert text.")
我怎样才能返回一个非一般的任务,其功能类似于在那里我可以等待,直到 dialogParameters.Closed
事件触发?我明白,我可以忽略布尔
是本code返回。我要寻找不同的解决方案比。
How can I return a non-generic Task that functions similarly where I can await it until dialogParameters.Closed
event fires? I understand that I could just ignore the bool
that is being returned in this code. I am looking for a different solution than that.
推荐答案
该方法可改为:
public Task ShowAlert(object message, string windowTitle)
任务&LT;布尔&GT;
从任务继承
这样你就可以返回任务&LT;布尔&GT;
,而只露出工作
给调用者
Task<bool>
inherits from Task
so you can return Task<bool>
while only exposing Task
to the caller
编辑:
我找到了微软的文档,<一个href="http://www.microsoft.com/en-us/download/details.aspx?id=19957">http://www.microsoft.com/en-us/download/details.aspx?id=19957,斯蒂芬Toub题为基于任务的异步模式',它有以下摘录建议同样的模式。
I found a Microsoft document, http://www.microsoft.com/en-us/download/details.aspx?id=19957, by Stephen Toub titled 'The Task-based Asynchronous pattern' and it has the following excerpt that recommends this same pattern.
有没有非泛型对口TaskCompletionSource&LT; TResult>。然而,任务和LT; TResult>源于任务,因此,一般TaskCompletionSource&LT; TResult>可用于I / O密集型的,仅仅通过利用源与虚拟TResult返回任务的方法(布尔是一个不错的缺省选择,和如果一个开发人员关注的任务的消费者它向下转换到一个任务&LT; TResult>,私人TResult类型都可以使用)
There is no non-generic counterpart to TaskCompletionSource<TResult>. However, Task<TResult> derives from Task, and thus the generic TaskCompletionSource<TResult> can be used for I/O-bound methods that simply return a Task by utilizing a source with a dummy TResult (Boolean is a good default choice, and if a developer is concerned about a consumer of the Task downcasting it to a Task<TResult>, a private TResult type may be used)
这篇关于非通用TaskCompletionSource或替代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!