簡體   English   中英

如何從主UI線程使用Parallel.ForEach

[英]How to use Parallel.ForEach from main UI thread

我嘗試使用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();
    }

得到錯誤后:

調用線程無法訪問此對象,因為另一個線程擁有它。

我也嘗試使用這個Parallel.ForEach與不同的Thread堅果得到了同樣的錯誤。

Parallel.ForEach的主體總是在線程池線程上執行。 您無法訪問那里的UI控件。 在UI線程上提取所需的所有值。 無論如何,這是更干凈的代碼:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM