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?
谢谢
答案 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;