是否有机会用 TPL 替换 while 循环?
我有两个 while 循环,它们将与 TPL 并行运行。
我的代码:
public void Initialize()
{
cts = new CancellationTokenSource();
ParallelOptions options = new ParallelOptions();
options.CancellationToken = cts.Token;
options.MaxDegreeOfParallelism = Environment.ProcessorCount;
task = Task.Factory.StartNew(() => Parallel.Invoke(options, Watcher1, Watcher2), cts.Token);
}
public void Watcher1()
{
//Can I replace this (with a TPL construct in the initialize method)?
while(true)
{
//Do sth.
}
}
public void Watcher2()
{
//Can I replace this (with a TPL construct in the initialize method)?
while(true)
{
//do sth
}
}
如果我可以安全地取消这两个操作,那就太好了。你能给我一些建议吗?
提前致谢。
亲切的问候,亲
I've a two while loops, which I will have run parallel with the TPL.
My code :
public void Initialize()
{
cts = new CancellationTokenSource();
ParallelOptions options = new ParallelOptions();
options.CancellationToken = cts.Token;
options.MaxDegreeOfParallelism = Environment.ProcessorCount;
task = Task.Factory.StartNew(() => Parallel.Invoke(options, Watcher1, Watcher2), cts.Token);
}
public void Watcher1()
{
//Can I replace this (with a TPL construct in the initialize method)?
while(true)
{
//Do sth.
}
}
public void Watcher2()
{
//Can I replace this (with a TPL construct in the initialize method)?
while(true)
{
//do sth
}
}
It would be nice, if I can cancel this two actions safely. Can you give me some advices?
Thanks in advance.
Kind regards, pro
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
CancellationTokenSource
来完成此操作,请参阅这篇文章了解详情You can do it using a
CancellationTokenSource
, see this article for details