我是.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) 我正在学习C#中的异步/等待模式.目前我正在尝试解决这样的问题:
有一个生产者(硬件设备)每秒生成1000个数据包.我需要将此数据记录到文件中.
该设备仅具有一次ReadAsync()
报告单个数据包的方法.
我需要缓冲数据包并按照它们生成的顺序将它们写入文件,每秒只执行一次.
如果写入过程没有在下一批数据包准备好写入时及时完成,则写操作应该失败.
到目前为止,我写了类似下面的内容.它有效,但我不确定这是否是解决问题的最佳方法.有任何意见或建议吗?在消费者需要汇总从生产者处收到的数据时,采用这种生产者/消费者问题的最佳做法是什么?
static async Task TestLogger(Device device, int seconds)
{
const int bufLength = 1000;
bool firstIteration = true;
Task writerTask = null;
using (var writer = new StreamWriter("test.log")))
{
do
{
var buffer = new byte[bufLength][];
for (int i = 0; i < bufLength; i++)
{
buffer[i] = await device.ReadAsync();
}
if (!firstIteration)
{
if (!writerTask.IsCompleted)
throw new Exception("Write Time Out!");
}
writerTask = Task.Run(() =>
{
foreach (var b in buffer)
writer.WriteLine(ToHexString(b)); …
Run Code Online (Sandbox Code Playgroud)