异步任务如何从方法返回值

时间:2013-11-28 11:29:45

标签: c#

CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

Task tasks = PeriodicTaskFactory.Start(() => LongRunningOperation(), intervalInMilliseconds: 1000, synchronous: false, cancelToken: cancellationTokenSource.Token);

int taskId = Task.WaitAny(tasks);

和我的LongRunningOperation

private String LongRunningOperation()
{
...
return proj.Name;
}

但问题是如何从LongRunningOperation中的Task方法获取价值。方法tasks.Results不存在。我希望从每个任务中获取价值。

我从这里获得PeriodicTaskFactory类

Is there a Task based replacement for System.Threading.Timer?

谢谢

1 个答案:

答案 0 :(得分:4)

Task没有返回值; Task<T>确实如此。

您必须修改PeriodicTaskFactory代码才能返回Task<T>,然后创建Task<string>个对象。 该方法还应该接受Func<T>(没有参数,返回T)而不是Action,它没有返回值。

public static Task<T> Start<T>(Func<T> func,
      int intervalInMilliseconds = Timeout.Infinite,
      int delayInMilliseconds = 0,
      int duration = Timeout.Infinite,
      int maxIterations = -1,
      bool synchronous = false,
      CancellationToken cancelToken = new CancellationToken(),
      TaskCreationOptions periodicTaskCreationOptions = TaskCreationOptions.None)
    {


Task<string> task = PeriodicTaskFactory.Start(LongRunningOperation, intervalInMilliseconds: 1000, synchronous: false, cancelToken: cancellationTokenSource.Token);

string result = task.Result;