调用从非异步方法异步方法 [英] Calling an async method from a non-async method
问题描述
在以下code,我尽量不工作每一个变化 - 无论是 DoSomething的():无效
,被称为书面,或 DoSomething的():任务
,被称为与 TaskEx.RunEx()
,一些尝试涉及 .GetAwaiter() .GetResult()
。看到错误包括:开始可能不会被称为与空操作的任务
,RunSynchronously可能无法绑定到委托的任务被称为
和的任务尚未完成
。
Every variation on the following code that I try doesn't work - whether DoSomething() : void
and is called as written, or DoSomething() : Task
and is called with TaskEx.RunEx()
, some attempt involving .GetAwaiter().GetResult()
. Errors seen include: "Start may not be called on a task with null action"
, "RunSynchronously may not be called on a task unbound to a delegate"
, and "The task has not yet completed"
.
class Program
{
static void Main(string[] args) // Starting from a non-async method
{
DoSomething();
Console.WriteLine("Press any key to quit.");
Console.ReadKey();
}
static async void DoSomething()
{
Console.WriteLine("Starting DoSomething ...");
var x = await PrepareAwaitable(1);
Console.WriteLine("::" + x);
var y = await PrepareAwaitable(2);
Console.WriteLine("::" + y);
}
static Task<string> PrepareAwaitable(int id)
{
return new Task<string>(() =>
{
return "Howdy " + id.ToString();
});
}
}
输出:
开始DoSomething的...
Starting DoSomething ...
preSS任意键退出。
Press any key to quit.
prepareAwaitable
的任务
的动作
稍后将变得更复杂。当这个动作完成,但久,需要,我希望在工作
(或其他框架机制),通过分配恢复你好......
为x,再后来到y。我真正想要做的是拦截期待已久的对象,处理它们,在我控制一段时间以后,重新开始与结果的延续( X
和是
)。但我还没有已经越来越上大步很远,所以我想开始变小。
PrepareAwaitable
's Task
's Action
will be more complicated later. When this action completes, however long that takes, I would expect the Task
(or other Framework mechanisms) to resume by assigning "Howdy ..."
to x, and then later to y. What I REALLY want to do is intercept the awaited objects, process them, and at some later time that I control, resume to the continuation with a result (x
and y
). But I haven't been getting very far on that big step, so I'm trying to start smaller.
推荐答案
您回来还没有开始的任务(即,他们是冷的任务);尝试用以下替换prepareAwaitable code:
The tasks you returned haven't started yet (i.e., they're "cold" tasks); try replacing the PrepareAwaitable code with the following:
static Task<string> PrepareAwaitable(int x)
{
return Task.Factory.StartNew<string>(() =>
{
return "Howdy " + x.ToString();
});
}
这篇关于调用从非异步方法异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!