berry wer
berry wer

Reputation: 647

How to use Parallel.ForEach from main UI thread

I try to do my stuff from the main Thread by using Parallel.ForEach:

private List<MyData> MyCollection;
private static CancellationTokenSource _tokenSource;

    private void Start()
    {
        ThreadStart threadStart = delegate
        {
            var token = _tokenSource.Token;
            Task.Factory.StartNew(() =>
            {
                try
                {
                    Parallel.ForEach(MyCollection,
                        new ParallelOptions
                        {
                            MaxDegreeOfParallelism = (int)nudConcurrentFiles.Value //limit number of parallel threads 
                        },
                        file =>
                        {
                            if (token.IsCancellationRequested)
                                return;
                            //do work...
                        });
                }
                catch (Exception e)
                { }

            }, _tokenSource.Token,
           TaskCreationOptions.None,
           TaskScheduler.Default).ContinueWith(
                t =>
                {

                }
            , TaskScheduler.FromCurrentSynchronizationContext() //to ContinueWith (update UI) from UI thread
            );
        };

        Thread thread = new Thread(threadStart);
        thread.IsBackground = true;
        thread.Start();
    }

And after got error:

The calling thread cannot access this object because a different thread owns it.

i also try to use this Parallel.ForEach with different Thread nut got the same error.

Upvotes: 4

Views: 1564

Answers (1)

usr
usr

Reputation: 171178

The body of Parallel.ForEach always executes on thread-pool threads. You can't access UI controls there. Pull all values that you need on the UI thread. This is cleaner code anyway:

var maxDOP = (int) nudConcurrentFiles.Value; //on UI thread

P.ForEach(..., () => { use maxDop here }); //in Task

Upvotes: 3

Related Questions