如何从主UI线程使用Parallel.ForEach

时间:2015-08-09 12:46:10

标签: c# multithreading task

我尝试使用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坚果得到相同的错误。

1 个答案:

答案 0 :(得分:3)

<form> <h1> My utter useless form </h1> <br> <table> <tr> <td> <button id="first" onclick="show()" >show</button> </td> <td> <button id="second" onclick="hide()">hide</button> </td> <td> <button id="third" hidden>effected</button> </td> </tr> </table> </form> 的主体总是在线程池线程上执行。您无法访问那里的UI控件。在UI线程上提取所需的所有值。无论如何,这是更干净的代码:

Parallel.ForEach