Jim*_*Jim 84 c# timeout timer .net-4.0 task-parallel-library
我是.Net 4.0的任务的新手,我无法找到我认为基于任务的替换或实现定时器,例如定期任务.有这样的事吗?
更新 我提出了我认为是我的需求的解决方案,即将"计时器"功能包装在具有子任务的任务中,所有任务都利用CancellationToken并返回任务以便能够参与进一步的任务步骤.
public static Task StartPeriodicTask(Action action, int intervalInMilliseconds, int delayInMilliseconds, CancellationToken cancelToken)
{
Action wrapperAction = () =>
{
if (cancelToken.IsCancellationRequested) { return; }
action();
};
Action mainAction = () =>
{
TaskCreationOptions attachedToParent = TaskCreationOptions.AttachedToParent;
if (cancelToken.IsCancellationRequested) { return; }
if (delayInMilliseconds > 0)
Thread.Sleep(delayInMilliseconds);
while (true)
{
if (cancelToken.IsCancellationRequested) { break; }
Task.Factory.StartNew(wrapperAction, cancelToken, attachedToParent, TaskScheduler.Current);
if (cancelToken.IsCancellationRequested || intervalInMilliseconds == Timeout.Infinite) { break; }
Thread.Sleep(intervalInMilliseconds);
}
};
return Task.Factory.StartNew(mainAction, cancelToken);
}
Run Code Online (Sandbox Code Playgroud)
Jef*_*eff 80
这取决于4.5,但这是有效的.
public class PeriodicTask
{
public static async Task Run(Action action, TimeSpan period, CancellationToken cancellationToken)
{
while(!cancellationToken.IsCancellationRequested)
{
await Task.Delay(period, cancellationToken);
if (!cancellationToken.IsCancellationRequested)
action();
}
}
public static Task Run(Action action, TimeSpan period)
{
return Run(action, period, CancellationToken.None);
}
}
Run Code Online (Sandbox Code Playgroud)
显然你可以添加一个带参数的泛型版本.这实际上类似于其他建议的方法,因为在引擎盖下Task.Delay使用计时器到期作为任务完成源.
Jim*_*Jim 56
更新 我将下面的答案标记为"答案",因为现在我们应该使用async/await模式.不需要再投票了.大声笑
正如Amy回答的那样,没有基于任务的定期/定时器实现.但是,根据我原来的UPDATE,我们已经将它演变成非常有用且经过生产测试的东西.以为我会分享:
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
Task perdiodicTask = PeriodicTaskFactory.Start(() =>
{
Console.WriteLine(DateTime.Now);
}, intervalInMilliseconds: 2000, // fire every two seconds...
maxIterations: 10); // for a total of 10 iterations...
perdiodicTask.ContinueWith(_ =>
{
Console.WriteLine("Finished!");
}).Wait();
}
}
/// <summary>
/// Factory class to create a periodic Task to simulate a <see cref="System.Threading.Timer"/> using <see cref="Task">Tasks.</see>
/// </summary>
public static class PeriodicTaskFactory
{
/// <summary>
/// Starts the periodic task.
/// </summary>
/// <param name="action">The action.</param>
/// <param name="intervalInMilliseconds">The interval in milliseconds.</param>
/// <param name="delayInMilliseconds">The delay in milliseconds, i.e. how long it waits to kick off the timer.</param>
/// <param name="duration">The duration.
/// <example>If the duration is set to 10 seconds, the maximum time this task is allowed to run is 10 seconds.</example></param>
/// <param name="maxIterations">The max iterations.</param>
/// <param name="synchronous">if set to <c>true</c> executes each period in a blocking fashion and each periodic execution of the task
/// is included in the total duration of the Task.</param>
/// <param name="cancelToken">The cancel token.</param>
/// <param name="periodicTaskCreationOptions"><see cref="TaskCreationOptions"/> used to create the task for executing the <see cref="Action"/>.</param>
/// <returns>A <see cref="Task"/></returns>
/// <remarks>
/// Exceptions that occur in the <paramref name="action"/> need to be handled in the action itself. These exceptions will not be
/// bubbled up to the periodic task.
/// </remarks>
public static Task Start(Action action,
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)
{
Stopwatch stopWatch = new Stopwatch();
Action wrapperAction = () =>
{
CheckIfCancelled(cancelToken);
action();
};
Action mainAction = () =>
{
MainPeriodicTaskAction(intervalInMilliseconds, delayInMilliseconds, duration, maxIterations, cancelToken, stopWatch, synchronous, wrapperAction, periodicTaskCreationOptions);
};
return Task.Factory.StartNew(mainAction, cancelToken, TaskCreationOptions.LongRunning, TaskScheduler.Current);
}
/// <summary>
/// Mains the periodic task action.
/// </summary>
/// <param name="intervalInMilliseconds">The interval in milliseconds.</param>
/// <param name="delayInMilliseconds">The delay in milliseconds.</param>
/// <param name="duration">The duration.</param>
/// <param name="maxIterations">The max iterations.</param>
/// <param name="cancelToken">The cancel token.</param>
/// <param name="stopWatch">The stop watch.</param>
/// <param name="synchronous">if set to <c>true</c> executes each period in a blocking fashion and each periodic execution of the task
/// is included in the total duration of the Task.</param>
/// <param name="wrapperAction">The wrapper action.</param>
/// <param name="periodicTaskCreationOptions"><see cref="TaskCreationOptions"/> used to create a sub task for executing the <see cref="Action"/>.</param>
private static void MainPeriodicTaskAction(int intervalInMilliseconds,
int delayInMilliseconds,
int duration,
int maxIterations,
CancellationToken cancelToken,
Stopwatch stopWatch,
bool synchronous,
Action wrapperAction,
TaskCreationOptions periodicTaskCreationOptions)
{
TaskCreationOptions subTaskCreationOptions = TaskCreationOptions.AttachedToParent | periodicTaskCreationOptions;
CheckIfCancelled(cancelToken);
if (delayInMilliseconds > 0)
{
Thread.Sleep(delayInMilliseconds);
}
if (maxIterations == 0) { return; }
int iteration = 0;
////////////////////////////////////////////////////////////////////////////
// using a ManualResetEventSlim as it is more efficient in small intervals.
// In the case where longer intervals are used, it will automatically use
// a standard WaitHandle....
// see http://msdn.microsoft.com/en-us/library/vstudio/5hbefs30(v=vs.100).aspx
using (ManualResetEventSlim periodResetEvent = new ManualResetEventSlim(false))
{
////////////////////////////////////////////////////////////
// Main periodic logic. Basically loop through this block
// executing the action
while (true)
{
CheckIfCancelled(cancelToken);
Task subTask = Task.Factory.StartNew(wrapperAction, cancelToken, subTaskCreationOptions, TaskScheduler.Current);
if (synchronous)
{
stopWatch.Start();
try
{
subTask.Wait(cancelToken);
}
catch { /* do not let an errant subtask to kill the periodic task...*/ }
stopWatch.Stop();
}
// use the same Timeout setting as the System.Threading.Timer, infinite timeout will execute only one iteration.
if (intervalInMilliseconds == Timeout.Infinite) { break; }
iteration++;
if (maxIterations > 0 && iteration >= maxIterations) { break; }
try
{
stopWatch.Start();
periodResetEvent.Wait(intervalInMilliseconds, cancelToken);
stopWatch.Stop();
}
finally
{
periodResetEvent.Reset();
}
CheckIfCancelled(cancelToken);
if (duration > 0 && stopWatch.ElapsedMilliseconds >= duration) { break; }
}
}
}
/// <summary>
/// Checks if cancelled.
/// </summary>
/// <param name="cancelToken">The cancel token.</param>
private static void CheckIfCancelled(CancellationToken cancellationToken)
{
if (cancellationToken == null)
throw new ArgumentNullException("cancellationToken");
cancellationToken.ThrowIfCancellationRequested();
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
2/18/2013 4:17:13 PM
2/18/2013 4:17:15 PM
2/18/2013 4:17:17 PM
2/18/2013 4:17:19 PM
2/18/2013 4:17:21 PM
2/18/2013 4:17:23 PM
2/18/2013 4:17:25 PM
2/18/2013 4:17:27 PM
2/18/2013 4:17:29 PM
2/18/2013 4:17:31 PM
Finished!
Press any key to continue . . .
Run Code Online (Sandbox Code Playgroud)
mst*_*one 12
它不完全在System.Threading.Tasks,但是Observable.Timer(或更简单Observable.Interval)来自Reactive Extensions库可能正是您正在寻找的.
到目前为止,我使用LongRunning TPL任务进行循环CPU绑定后台工作而不是线程计时器,因为:
但是,TPL解决方案始终声称专用线程在等待下一个操作(大多数时间)时不是必需的.我想使用建议的Jeff解决方案在后台执行CPU绑定循环工作,因为它只需要一个线程池线程,当有工作要做时,这对于可伸缩性更好(特别是当间隔时间很长时).
要实现这一点,我建议4个适应:
ConfigureAwait(false)到线程池线程上Task.Delay()执行doWork操作,否则doWork将在调用线程上执行,这不是并行性的想法doWork使其取消任务关于第2点我不确定,异步等待是否还需要TaskCanceledExecption,还是最佳做法?
public static async Task Run(Action<object, CancellationToken> doWork, object taskState, TimeSpan period, CancellationToken cancellationToken)
{
do
{
await Task.Delay(period, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
doWork(taskState, cancellationToken);
}
while (true);
}
Run Code Online (Sandbox Code Playgroud)
请对拟议的解决方案发表意见......
更新2016-8-30
上面的解决方案不是立即调用,doWork()而是从await Task.Delay().ConfigureAwait(false)实现线程切换开始doWork().下面的解决方案通过将第一个doWork()调用包装在a中Task.Run()并等待它来克服这个问题.
下面是改进的async\await替换,Threading.Timer它执行可取消的循环工作并且是可伸缩的(与TPL解决方案相比),因为它在等待下一个操作时不占用任何线程.
注意,与Timer相反,等待时间(period)是恒定的而不是循环时间; 循环时间是等待时间和持续时间doWork()可以变化的总和.
public static async Task Run(Action<object, CancellationToken> doWork, object taskState, TimeSpan period, CancellationToken cancellationToken)
{
await Task.Run(() => doWork(taskState, cancellationToken), cancellationToken).ConfigureAwait(false);
do
{
await Task.Delay(period, cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
doWork(taskState, cancellationToken);
}
while (true);
}
Run Code Online (Sandbox Code Playgroud)
我需要从同步方法触发重复的异步任务。
public static class PeriodicTask
{
public static async Task Run(
Func<Task> action,
TimeSpan period,
CancellationToken cancellationToken = default(CancellationToken))
{
while (!cancellationToken.IsCancellationRequested)
{
Stopwatch stopwatch = Stopwatch.StartNew();
if (!cancellationToken.IsCancellationRequested)
await action();
stopwatch.Stop();
await Task.Delay(period - stopwatch.Elapsed, cancellationToken);
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是杰夫答案的改编。它被更改为接受 aFunc<Task>
它还通过从下一个延迟的时间段中扣除任务的运行时间来确保该时间段是它运行的频率。
class Program
{
static void Main(string[] args)
{
PeriodicTask
.Run(GetSomething, TimeSpan.FromSeconds(3))
.GetAwaiter()
.GetResult();
}
static async Task GetSomething()
{
await Task.Delay(TimeSpan.FromSeconds(1));
Console.WriteLine($"Hi {DateTime.UtcNow}");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
58848 次 |
| 最近记录: |