首页 / C# / 如何使用C#访问此Task返回值?
如何使用C#访问此Task返回值?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何使用C#访问此Task返回值?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1738字,纯文字阅读大概需要3分钟。
内容图文
![如何使用C#访问此Task返回值?](/upload/InfoBanner/zyjiaocheng/685/0882d9ec63c64cdaa4b43fc5ae8c19a6.jpg)
我在这里关注@StephenHaunts在此发布的博客https://stephenhaunts.com/2014/10/10/simple-async-await-example-for-asynchronous-programming/#comments
LongRunningOperation内部代码中最后一个return语句的作用是什么.
private static async Task<string> LongRunningOperation()
{
int counter;
for (counter = 0; counter < 50000; counter++)
{
Console.WriteLine(counter);
}
return "Counter = " + counter;
}
现在我知道的是:
>当我在Task.Run中调用此LongrunningOperation时,它应返回默认情况下此等待方法返回的内容.那为什么不这样做呢.
>如果我使用Task.Result属性,则它将同步运行并阻止调用线程,这是不推荐的.
我想问的是:
>如何在呼叫地点打印此返回值?
>为什么@Stephen在不需要它时编写了该声明?
提前致谢.
解决方法:
What is the purpose of last
return
statement in the code, insideLongRunningOperation
.
返回字符串“ Counter = 50000”并演示循环已完成.这不是很有用,但是很明显,这是一个玩具示例.您可以将方法声明为静态异步任务,而不是静态异步Task< string>.而不返回值.
As I am calling this
LongrunningOperation
insideTask.Run
, it should return whatever this awaited method is returning by default. Then Why it is not doing that.
是什么让您认为它没有这样做?以下代码段不返回预期结果吗?
string s = await Task.Run(() => LongrunningOperation());
// s should now contain "Counter = 50000".
注意:不等待就调用Task.Run将返回可能未完成的任务,而不是结果.
If I use
Task.Result
property then It’ll run behave synchronously and block calling thread, which is not recommended.
就是这样,这就是为什么您不应该这样做.
How I’ll get this returned value printed at calling spot?
通过对返回值进行处理.通过将其分配给字符串(如上所示),或直接将其打印出来:
Console.WriteLine(await Task.Run(() => LongrunningOperation()));
And why @Stephen have written that statement when there is no need of it?
那,你得问斯蒂芬.
内容总结
以上是互联网集市为您收集整理的如何使用C#访问此Task返回值?全部内容,希望文章能够帮你解决如何使用C#访问此Task返回值?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。