等待新的Task< T>(...):任务不运行?

编程入门 行业动态 更新时间:2024-10-25 12:16:42
本文介绍了等待新的Task< T>(...):任务不运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在此处询问的问题的延续:

A continuation of a question asked here :

在上述问题中,我具有以下函数,该函数返回Task类型的对象(用于增量测试):

In the aforementioned question I have the following function which returns an object of type Task (for incremental testing purposes) :

private static Task<object> GetInstance( ) { return new Task<object>( (Func<Task<object>>)(async ( ) => { await SimpleMessage.ShowAsync( "TEST" ); return new object( ); } ) ); }

当我调用await GetInstance( );时,将调用该函数(并且我假定由于未引发异常而返回了任务),但是任务只是坐在那里.

When I call await GetInstance( );, the function is called (and I assume the task is returned since no exception is thrown) but then the task just sits there.

我只能猜测自己当时做错了.

I can only guess I am doing this wrong then.

我不希望此函数返回已 已在运行 (即 IMPERATIVE )的任务)

I do not want this function to return a task that is already running ( that is IMPERATIVE ).

如何异步运行此函数返回的任务?

How do I asynchronously run the task returned by this function?

推荐答案

要创建已开始的任务

尝试创建如下任务:

Task.Factory.StartNew<object>((Func<Task<object>>) ...);

要创建任务而不启动它

如果您不希望启动任务,只需按原样使用new Task<object>(...)即可,但是在等待该任务之前,您需要在该任务上调用Start()方法!

If you don't want the task started, just use new Task<object>(...) as you were using, but then you need to call Start() method on that task before awaiting it!

[参考]

我的推荐

只需创建一个返回匿名函数的方法,如下所示:

Just make a method that returns the anonymous function, like this:

private static Func<object> GetFunction( ) { return (Func<object>)(( ) => { SimpleMessage.Show( "TEST" ); return new object( ); } ); }

然后获取它,并在需要时在新的Task中运行它(还要注意,我已经从lambda表达式中删除了async/await,因为您已经将它放入了Task中了):

Then get it and run it in a new Task whenever you need it (Also notice that I removed the async/await from the lambda expression, since you are putting it into a Task already):

Task.Factory.StartNew<object>(GetFunction());

这样做的一个好处是,您也可以将其调用而无需将其放入Task:

One advantage to this is that you can also call it without putting it into a Task:

GetFunction()();

更多推荐

等待新的Task&lt; T&gt;(...):任务不运行?

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

发布评论

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

>www.elefans.com

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