如何使两个任务 运行 均匀分配 cpu 时间
How to make two Tasks run with an even distribution of cpu time
它们一开始是均匀的,但最终 processTasks 永远不会被命中。
当任务很简单时,最初我将其作为两个线程。有人建议 async/await 任务,作为 c# 的新手,我没有理由怀疑它们。
Task monitorTasks= new Task (monitor.start );
Task processTasks= new Task( () => processor.process(ref param, param2) );
monitorTasks.Start();
processTasks.Start();
await processTasks;
我执行错了吗? 运行 两个任务时我的问题是不可避免的吗?它们应该是线程吗?如何避免。
编辑
澄清一下。这些任务永远不会结束。它们将始终在处理和监视的同时触发通知观察者监视器输出或处理器输出的事件。
如果您在 Task.WhenAll
上等待,那么它会一直等到所有任务都处理完毕
await Task.WhenAll(monitorTasks, processTasks)
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall(v=vs.110).aspx
Task.WaitAll
阻塞当前线程,直到一切都完成。
Task.WhenAll
returns一个任务,表示等待一切完成的动作。
Creates a task that will complete when all of the Task objects in an
enumerable collection have completed.
Waits for all of the provided Task objects to complete execution.
如果你想阻止等待启动的任务(这似乎是你想要的)
Task monitorTasks= new Task (monitor.start );
Task processTasks= new Task( () => processor.process(ref param, param2) );
monitorTasks.Start();
processTasks.Start();
Task.WaitAll(new Task[]{monitorTasks,processTasks})
如果您使用的是 async
await
,请参阅 Asynchronous programming with async and await
然后你可以这样做
var task1 = DoWorkAsync();
var task2 = DoMoreWorkAsync();
await Task.WhenAll(task1, task2);
我无法将任务均匀分配给 运行。
监控任务不断被淹没,而处理器任务获取任务的频率降低,这就是我怀疑监控任务接管的时候。
既然没人能帮我,
我的解决方案是将它们转回线程,并将 threads.Lower 的优先级设置为高于监视器任务的正常优先级,并高于处理器任务的正常优先级。
这似乎解决了我的问题。
它们一开始是均匀的,但最终 processTasks 永远不会被命中。 当任务很简单时,最初我将其作为两个线程。有人建议 async/await 任务,作为 c# 的新手,我没有理由怀疑它们。
Task monitorTasks= new Task (monitor.start );
Task processTasks= new Task( () => processor.process(ref param, param2) );
monitorTasks.Start();
processTasks.Start();
await processTasks;
我执行错了吗? 运行 两个任务时我的问题是不可避免的吗?它们应该是线程吗?如何避免。
编辑
澄清一下。这些任务永远不会结束。它们将始终在处理和监视的同时触发通知观察者监视器输出或处理器输出的事件。
如果您在 Task.WhenAll
上等待,那么它会一直等到所有任务都处理完毕
await Task.WhenAll(monitorTasks, processTasks)
https://msdn.microsoft.com/en-us/library/system.threading.tasks.task.whenall(v=vs.110).aspx
Task.WaitAll
阻塞当前线程,直到一切都完成。
Task.WhenAll
returns一个任务,表示等待一切完成的动作。
Creates a task that will complete when all of the Task objects in an enumerable collection have completed.
Waits for all of the provided Task objects to complete execution.
如果你想阻止等待启动的任务(这似乎是你想要的)
Task monitorTasks= new Task (monitor.start );
Task processTasks= new Task( () => processor.process(ref param, param2) );
monitorTasks.Start();
processTasks.Start();
Task.WaitAll(new Task[]{monitorTasks,processTasks})
如果您使用的是 async
await
,请参阅 Asynchronous programming with async and await
然后你可以这样做
var task1 = DoWorkAsync();
var task2 = DoMoreWorkAsync();
await Task.WhenAll(task1, task2);
我无法将任务均匀分配给 运行。 监控任务不断被淹没,而处理器任务获取任务的频率降低,这就是我怀疑监控任务接管的时候。
既然没人能帮我, 我的解决方案是将它们转回线程,并将 threads.Lower 的优先级设置为高于监视器任务的正常优先级,并高于处理器任务的正常优先级。 这似乎解决了我的问题。