调用从非异步方法异步方法

编程入门 行业动态 更新时间:2024-10-24 19:13:57
本文介绍了调用从非异步方法异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在以下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(); }); }

更多推荐

调用从非异步方法异步方法

本文发布于:2023-11-14 13:35:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587355.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!