简体   繁体   中英

using TPL ActionBlock, Can I add a new item after the job completed

I am using TPL ActionBlock in my application to implement parallelism.

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. So the idea is like whatever comes from the user, show it in the UI and perform things parallely in the background.

Now, in the UI(window) I have a stop button to stop the user input. Whenever I click this function, the user will not be able to input anything more. And now I am calling ActionBlock.Complete method as well to check the Queue/Block is completed or not.

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. Is this really a good idea or I have to call the ActionBlock.Complete() inside the constructor or where the ActionBlock is defined.

public void CheckJobQ()
{
    _jobs.Complete();
    _jobs.Completion.Wait();
}

and _jobs is the 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM