Reputation: 20936
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
Task tasks = PeriodicTaskFactory.Start(() => LongRunningOperation(), intervalInMilliseconds: 1000, synchronous: false, cancelToken: cancellationTokenSource.Token);
int taskId = Task.WaitAny(tasks);
and my LongRunningOperation
private String LongRunningOperation()
{
...
return proj.Name;
}
but the problem is how to get value from LongRunningOperation
method back in Task
. Method tasks.Results
not exists. And I want to get back the value from each Task.
I get PeriodicTaskFactory class from here
Is there a Task based replacement for System.Threading.Timer?
Thank you
Upvotes: 1
Views: 6154
Reputation: 68750
Task
has no return value; Task<T>
does.
You have to modify the PeriodicTaskFactory
code to return Task<T>
instead, and then create Task<string>
objects.
The method should also accept a Func<T>
(has no arguments, returns T) instead of an Action
, which has no return value.
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;
Upvotes: 4