非通用 TaskCompletionSource 或替代 [英] Non-Generic TaskCompletionSource or alternative
问题描述
我正在使用通常异步显示的警报窗口 (Telerik WPF)(代码在打开时继续运行),我想通过使用 async/await 使其同步.
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
一起工作,但那个类是通用的,当我想要的只是一个普通的 Task
时,它返回一个像 Task
这样的对象代码>,没有返回值.
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;
}
调用该方法的代码是
await MessageBoxService.ShowAlert("The alert text.")
如何返回一个功能类似的非通用任务,我可以等待直到 dialogParameters.Closed
事件触发?我知道我可以忽略此代码中返回的 bool
.我正在寻找与此不同的解决方案.
How can I return a non-generic Task that functions similarly which I can await until the 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)
Task
继承自 Task
所以你可以返回 Task
而只暴露 Task
给来电者
Task<bool>
inherits from Task
so you can return Task<bool>
while only exposing Task
to the caller
我找到了一个 Microsoft 文档,http://www.microsoft.com/en-us/download/details.aspx?id=19957,Stephen 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
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屋!