在 C# 的 Windows 服务中使用 TPL 的基本设计模式
本文关键字:TPL 设计模式 Windows 服务 | 更新日期: 2023-09-27 18:33:46
我正在尝试构建Windows服务,该服务需要某种并行性来汇集来自不同ftp源的文件。为了启动多个ftp下载,我正在寻找TPL库来轻松执行每个循环并使并行性变得完全容易。但是当我搜索如何启动或停止我的服务时,我认为最好的机会是在方法中创建新线程OnStart()
如此处所述 https://stackoverflow.com/a/4865893/69433
阅读有关TPL的信息,总是注意到TPL比手动线程和手动停止线程更高级。
我没有找到任何描述如何在WindowsService中制作TPL循环的示例帖子?
我的代码:
protected override void OnStart(string[] args)
{
_thread = new Thread(WorkerThreadFunc);
_thread.Name = "My Worker Thread";
_thread.IsBackground = true;
_thread.Start();
}
在里面WorkerThreadFunc
做中小企业那种TPL
private void WorkerThreadFunc()
{
foreach (string path in paths)
{
string pathCopy = path;
var task = Task.Factory.StartNew(() =>
{
Boolean taskResult = ProcessPicture(pathCopy);
return taskResult;
});
task.ContinueWith(t => result &= t.Result);
tasks.Add(task);
}
}
或者我应该启动我的WorkerThreadFunc作为TASK?
这里的警告不仅是你如何启动你的工作线程,还有你如何实际停止它。
除了任务本身,TPL 还为您提供了一种非常方便的通过使用CancellationToken
和CancellationTokenSource
对象取消任务的方法。
使用 TPL 启动和停止窗口服务
若要将此技术应用于 Windows 服务,基本上需要执行以下操作:
private CancellationTokenSource tokenSource;
private Task backgroundTask;
protected override void OnStart(string[] args)
{
tokenSource = new CancellationTokenSource();
var cancellation = tokenSource.Token;
backgroundTask = Task.Factory.StartNew(() => WorkerThreadFunc(cancellation),
cancellation,
TaskCreationOptions.LongRunning,
TaskScheduler.Default);
}
笔记:
-
TaskCreationOptions.LongRunning
提示任务计划程序此任务可能需要单独的线程,并避免将其放在 ThreadPool 上(这样它就不会阻塞池中的其他项目( -
CancellationToken
被传递给 WorkerThreadFunc,因为这是通知它停止工作的方式 - 请参阅下面的取消部分
在 OnStop 方法中,您可以触发取消并等待任务完成:
protected override void OnStop()
{
bool finishedSuccessfully = false;
try
{
tokenSource.Cancel();
var timeout = TimeSpan.FromSeconds(3);
finishedSuccessfully = backgroundTask.Wait(timeout);
}
finally
{
if (finishedSuccessfully == false)
{
// Task didn't complete during reasonable amount of time
// Fix your cancellation handling in WorkerThreadFunc or ProcessPicture
}
}
}
取消
通过调用tokenSource.Cancel();
我们只需告诉此tokenSource
发出的每个CancellationToken
都被取消,并且接受此类令牌的每个方法(如您的 WorkerThreadFunc(现在都应该停止其工作。
处理取消特定于实现,但一般规则是方法应监视取消令牌状态,并能够在合理的时间内停止其工作。这种方法要求您在逻辑上将工作拆分为较小的部分,这样您就不会停留在做一些需要大量时间才能完成的工作上,并且在请求取消时不会开始任何新工作。
查看您的 WorkerThreadFunc 代码,您可以考虑在执行每个新ProcessPicture
任务之前检查取消,例如:
private List<Task> tasks = new List<Task>();
private void WorkerThreadFunc(CancellationToken token)
{
foreach (string path in paths)
{
if (token.IsCancellationRequested)
{
// you may also want to pass a timeout value here to handle 'stuck' processing
Task.WaitAll(tasks.ToArray());
// no more new tasks
break;
}
string pathCopy = path;
var task = Task.Factory.StartNew(() =>
{
Boolean taskResult = ProcessPicture(pathCopy, token); // <-- consider a cancellation here
return taskResult;
}, token); // <<--- using overload with cancellation token
task.ContinueWith(t => result &= t.Result);
tasks.Add(task);
}
}
如果ProcessPicture
需要很长时间才能完成,您可能还需要在其中添加取消支持。与WorkerThreadFunc类似,您应该考虑ProcessPicture
实现。这里的关键思想是找到一个可以安全地停止工作并从方法返回的地方。我的意思是安全 - 不会让系统或数据处于损坏状态。
除了在 WorkerThreadFunc 中监视IsCancellationRequested
之外,您还可以Register
请求取消时将执行的回调,以执行其他一些操作,例如清理等:
token.Register(CancellationCallback);
和
private void CancellationCallback()
{
// wait for all tasks to finish
// cleanup
}