我有一个“高精度”计时器类,我需要能够启动,停止和放大暂停/恢复。为此,我将在互联网上找到的几个不同的例子捆绑在一起,但我不确定我是否正在使用asnyc / await正确的任务。
以下是我的相关代码:
//based on http://haukcode.wordpress.com/2013/01/29/high-precision-timer-in-netc/
public class HighPrecisionTimer : IDisposable
{
Task _task;
CancellationTokenSource _cancelSource;
//based on http://blogs.msdn.com/b/pfxteam/archive/2013/01/13/cooperatively-pausing-async-methods.aspx
PauseTokenSource _pauseSource;
Stopwatch _watch;
Stopwatch Watch { get { return _watch ?? (_watch = Stopwatch.StartNew()); } }
public bool IsPaused
{
get { return _pauseSource != null && _pauseSource.IsPaused; }
private set
{
if (value)
{
_pauseSource = new PauseTokenSource();
}
else
{
_pauseSource.IsPaused = false;
}
}
}
public bool IsRunning { get { return !IsPaused && _task != null && _task.Status == TaskStatus.Running; } }
public void Start()
{
if (IsPaused)
{
IsPaused = false;
}
else if (!IsRunning)
{
_cancelSource = new CancellationTokenSource();
_task = new Task(ExecuteAsync, _cancelSource.Token, TaskCreationOptions.LongRunning);
_task.Start();
}
}
public void Stop()
{
if (_cancelSource != null)
{
_cancelSource.Cancel();
}
}
public void Pause()
{
if (!IsPaused)
{
if (_watch != null)
{
_watch.Stop();
}
}
IsPaused = !IsPaused;
}
async void ExecuteAsync()
{
while (!_cancelSource.IsCancellationRequested)
{
if (_pauseSource != null && _pauseSource.IsPaused)
{
await _pauseSource.Token.WaitWhilePausedAsync();
}
// DO CUSTOM TIMER STUFF...
}
if (_watch != null)
{
_watch.Stop();
_watch = null;
}
_cancelSource = null;
_pauseSource = null;
}
public void Dispose()
{
if (IsRunning)
{
_cancelSource.Cancel();
}
}
}
任何人都可以看看,并提供一些关于我是否正确这样做的指示?
更新
我已尝试根据下面的Noseratio评论修改我的代码,但我仍然无法弄清楚语法。每次尝试将 ExecuteAsync()方法传递给 TaskFactory.StartNew 或 Task.Run 时,都会导致编译错误,如下所示:< / p>
“以下方法或属性之间的调用不明确:TaskFactory.StartNew(Action,CancellationToken ...)和TaskFactory.StartNew&lt; Task&gt;(Func&lt; Task&gt;,CancellationToken ...)”。
最后,有没有办法在不必提供TaskScheduler的情况下指定LongRunning TaskCreationOption?
async **Task** ExecuteAsync()
{
while (!_cancelSource.IsCancellationRequested)
{
if (_pauseSource != null && _pauseSource.IsPaused)
{
await _pauseSource.Token.WaitWhilePausedAsync();
}
//...
}
}
public void Start()
{
//_task = Task.Factory.StartNew(ExecuteAsync, _cancelSource.Token, TaskCreationOptions.LongRunning, null);
//_task = Task.Factory.StartNew(ExecuteAsync, _cancelSource.Token);
//_task = Task.Run(ExecuteAsync, _cancelSource.Token);
}
更新2
我认为我已经缩小了范围,但仍然不确定正确的语法。这是创建任务的正确方法,以便消费者/调用代码继续运行,任务启动并在新的异步线程上启动吗?
_task = Task.Run(async () => await ExecuteAsync, _cancelSource.Token);
//**OR**
_task = Task.Factory.StartNew(async () => await ExecuteAsync, _cancelSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
答案 0 :(得分:16)
以下是一些要点:
async void
方法仅适用于异步事件处理程序(more info)。您的async void ExecuteAsync()
会立即返回(代码流一旦到达await _pauseSource
)。从本质上讲,您的_task
之后处于已完成状态,而ExecuteAsync
的其余部分将在未被观察的情况下执行(因为它是void
)。它甚至可能根本不会继续执行,具体取决于主线程(以及进程)何时终止。
鉴于此,您应该将其设为async Task ExecuteAsync()
,并使用Task.Run
或Task.Factory.StartNew
代替new Task
来启动它。因为您希望任务的操作方法为async
,所以您将在此处理嵌套任务,即Task<Task>
,Task.Run
会自动为您解开。可以找到更多信息here和here。
PauseTokenSource
采用以下方法(按设计,AFAIU):代码的消费者方(调用Pause
的方)实际上只请求暂停,但不同步在上面。它将在Pause
之后继续执行,即使生产者方可能尚未达到等待状态,即await _pauseSource.Token.WaitWhilePausedAsync()
。这可能适用于您的应用程序逻辑,但您应该了解它。更多信息here。
[更新] 以下是使用Factory.StartNew
的正确语法。请注意Task<Task>
和task.Unwrap
。另请注意_task.Wait()
中的Stop
,确保在Stop
返回时完成任务(以类似于Thread.Join
的方式)。此外,TaskScheduler.Default
用于指示Factory.StartNew
使用线程池调度程序。如果您从另一个任务中创建HighPrecisionTimer
对象,这又很重要,而该任务又是在具有非默认同步上下文的线程上创建的,例如, UI线程(更多信息here和here)。
using System;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication
{
public class HighPrecisionTimer
{
Task _task;
CancellationTokenSource _cancelSource;
public void Start()
{
_cancelSource = new CancellationTokenSource();
Task<Task> task = Task.Factory.StartNew(
function: ExecuteAsync,
cancellationToken: _cancelSource.Token,
creationOptions: TaskCreationOptions.LongRunning,
scheduler: TaskScheduler.Default);
_task = task.Unwrap();
}
public void Stop()
{
_cancelSource.Cancel(); // request the cancellation
_task.Wait(); // wait for the task to complete
}
async Task ExecuteAsync()
{
Console.WriteLine("Enter ExecuteAsync");
while (!_cancelSource.IsCancellationRequested)
{
await Task.Delay(42); // for testing
// DO CUSTOM TIMER STUFF...
}
Console.WriteLine("Exit ExecuteAsync");
}
}
class Program
{
public static void Main()
{
var highPrecisionTimer = new HighPrecisionTimer();
Console.WriteLine("Start timer");
highPrecisionTimer.Start();
Thread.Sleep(2000);
Console.WriteLine("Stop timer");
highPrecisionTimer.Stop();
Console.WriteLine("Press Enter to exit...");
Console.ReadLine();
}
}
}