开发者

Parallel.ForEach() .... how best to terminate loop externally?

开发者 https://www.devze.com 2023-02-05 06:51 出处:网络
I have an application whereby I download and process approximately 7,800 URL\'s using a Paraller.ForEach() loop.Using this technique has allowed my computer to complete this operation in about 4.5 min

I have an application whereby I download and process approximately 7,800 URL's using a Paraller.ForEach() loop. Using this technique has allowed my computer to complete this operation in about 4.5 minutes (is used to take almost 28 minutes on average).

As this is running inside a WinForms application I allow the user to "stop" the process early by simply clicking a stop button, which will in turn set a volatile boolean variable to 'false'. At the top of my Parallel.ForEach() loop I check the state of that variable, and if it has been set to 'false' I simply call the ParallelLoopState.Stop() method. My next code block inside the loop only runs if the ParallelLoopState has not been stopped.

Works great. Have experienced zero problems using this implementation for the 3 weeks I've been using it.

But I was just reading and came across the "CancellationTokenSource" and "CancellationToken" classes and discovered these were designed to essentially perform the same act ... to allow a Parallel loop to be cancelled externally.

Can anyone tell me if they foresee a problem with me continuing to use my existing implementation?

Parallel.ForEach(searchList, (url, state) =>
{
    if (!this.isSearching)
    开发者_JAVA百科{
        state.Stop();

        OnSearchEvent(new SearchStatusEventArgs(SearchState.STOP_REQUESTED, ......));
    }

    if (!state.IsStopped)
    {
        // continue on with regular processing .......
    }
});


Looks fine to me! The CancellationTokenSource and CancellationToken are really for use with Tasks especially where tasks are linked together via ContinueWith. From there, you can interrogate the Token (thread safe) and throw an exception or quit the thread in exactly the same way you are already doing it.

Unless you go down the route of complicated task chaining and closures, then I'd say there is no need to complicate things!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号