如何从线程任务返回数据
我目前正在尝试使用 .net 任务来运行长方法。我需要能够从任务返回数据。我想每次在新任务中运行时多次调用此方法。但是,使用 Task.Result 属性返回数据会使每个任务等待完成。
例如,目前如果执行类似以下操作:
public void RunTask()
{
var task = Task.Factory.StartNew(() =>
{
return LongMethod()
});
Console.WriteLine(task.Result);
}
并多次调用它,每次花费不同的时间,则它会等待每个任务完成,然后再执行下一个任务。
是否可以多次调用我的 RunTask 方法,每次都返回一个结果,而不必等待每个任务按顺序完成?
I am currently trying to use a .net Task to run a long method. I need to be able to return data from the task. I would like to call this method multiple times each time running it in a new task. However, returning data using the Task.Result property makes each task wait until complete.
For example currently if do something like this :
public void RunTask()
{
var task = Task.Factory.StartNew(() =>
{
return LongMethod()
});
Console.WriteLine(task.Result);
}
and call it multiple times, each time taking a different amount of time, it is waits for each Task to complete before executing the next.
Is it possible to call my RunTask method multiple times, each time returning a result without having to wait for each task to complete in order ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的。当您对
Task
调用task.Result
时,它将阻塞,直到出现结果。如果您想使其完全异步,您可以更改方法以直接返回
Task
,并在调用者级别“阻止”,或者使用延续:Yes. When you call
task.Result
on aTask<T>
, it will block until a result occurs.If you want to make this completely asynchronous, you could either change your method to return the
Task<T>
directly, and "block" at the caller's level, or use a continuation: