[英]using TPL ActionBlock, Can I add a new item after the job completed
I am using TPL ActionBlock
in my application to implement parallelism.我在我的应用程序中使用 TPL
ActionBlock
来实现并行性。
I have an application that will perform an action based on user input.我有一个应用程序将根据用户输入执行操作。 Sometimes the action takes more time and sometimes not, based on the input.
根据输入,有时操作需要更多时间,有时不需要。
So the real purpose of the ActionBlock
is that whenever an input came I want to show it in the UI first (having a window), then in the background perform the action.所以
ActionBlock
的真正目的是每当输入出现时,我想首先在 UI 中显示它(有一个窗口),然后在后台执行操作。 So the idea is like whatever comes from the user, show it in the UI and perform things parallely in the background.所以这个想法就像来自用户的任何东西,在 UI 中显示并在后台并行执行。
Now, in the UI(window) I have a stop button to stop the user input.现在,在 UI(窗口)中,我有一个停止按钮来停止用户输入。 Whenever I click this function, the user will not be able to input anything more.
每当我单击此 function 时,用户将无法再输入任何内容。 And now I am calling
ActionBlock.Complete
method as well to check the Queue/Block is completed or not.现在我也在调用
ActionBlock.Complete
方法来检查队列/块是否完成。
So here my doubt is,所以我的疑问是,
I am calling ActionBlock.Complete()
as a separate method based on the stop button click, which will wait for the job to complete then do some work and close the UI.我将
ActionBlock.Complete()
作为基于停止按钮单击的单独方法调用,它将等待作业完成然后做一些工作并关闭 UI。 Is this really a good idea or I have to call the ActionBlock.Complete()
inside the constructor or where the ActionBlock
is defined.这真的是一个好主意,还是我必须在构造函数内或定义
ActionBlock
的地方调用ActionBlock.Complete()
。
public void CheckJobQ()
{
_jobs.Complete();
_jobs.Completion.Wait();
}
and _jobs
is the ActionBlock
:和
_jobs
是ActionBlock
:
var executionDataflowBlockOptions = new ExecutionDataflowBlockOptions()
{
MaxDegreeOfParallelism = 100
};
_jobs = new ActionBlock<Tuple<Action<Element>, Element>>((job) =>
{
job.Item1.Invoke(job.Item2);
}, executionDataflowBlockOptions);
All dataflow blocks are thread-safe, so calling:所有数据流块都是线程安全的,因此调用:
_jobs.Complete();
...from the action of an ActionBlock
is permitted and totally fine. ...从一个
ActionBlock
的动作是允许的,完全没问题。
On the other hand the dataflow blocks are not deadlock-safe.另一方面,数据流块不是死锁安全的。 So if you wait for the completion of the block while processing an element:
因此,如果您在处理元素时等待块的完成:
_jobs.Completion.Wait();
...you have probably shot yourself in the foot. ...您可能已经在脚上开枪了。 The action will never be completed, and neither will the block itself.
该动作将永远不会完成,块本身也不会。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.