任务parallel.invoke()上的问题 [英] Problem on task parallel.invoke()

查看:176
本文介绍了任务parallel.invoke()上的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行第一个循环时(i = 0)

when execute the first loop (i = 0)

System.InvalidOperationException: 'Invalid cross-thread operation: the 'boxframe' control was accessed from a different thread than the one from which the creation was performed.'





我尝试了什么:





What I have tried:

private void CreaThumbs(string path)
{
 .....
            Action[] actions = new Action[3];     
            actions[0] = () => CreaBox(i);
            actions[1] = () => CreaImage(i, path, FileImg);
            actions[2] = () => CreaButton(i);

for (i = 0; i < elementi; i++)
  {
      ...........
      (Parallel.Invoke(actions);
      ..........
  }

private void CreaBox(int i)
        {
            boxCornice[i] = new Label();
	    ....
        }

private void CreaImmage(int i, string path, string NameFile)
        {
            //create PictureBox
            pictBox[i] = new PictureBox();
            pictBox[i].Parent = boxCornice[i];  //controllo associato            
            ........
	}            

private void CreaButton(int i)
        {
            btnRotateSx[i] = new PictureBox();
            btnRotateSx[i].Parent = boxCornice[i];
	    ....
	    btnRotateDx[i] = new PictureBox();
            btnRotateDx[i].Parent = boxCornice[i];
	    ....

        }
...
}

推荐答案

您只能访问(或者crea te)UI控件来自创建它们的线程 - UI线程。如果您尝试从非UI线程访问它们,您将获得一个cress线程异常。



您可以将它们调用回UI线程,但是..因为所有的多线程代码都试图创建UI控件,所以你要做的就是为你的代码添加额外的处理级别,最后仍然会在同一个线程上按顺序执行相同的任务。



最有可能的是,你试图这样做是为了同时创建大量的缩略图:这是行不通的。完全转储图片框,然后在其Paint事件中手动将缩略图图像绘制到单个控件上。它应该比创建通用控件(如PictureBoxes)快得多。
You can only access (or create) UI controls from the thread on which they were created - the UI thread. If you try to access them from a non-UI thread, you will get a cress threading exception.

You can Invoke them back to the UI thread, but ... since all of your multithreaded code is trying to create UI controls, all you would do is add an extra level of processing to your code and still end up with the same tasks happening in sequence on the same thread.

Most likely, you are trying to do this in order to create a lot of thumbnails at the same time: that won't work. Dump the Picture boxes completely, and manually draw the thumbnail images onto a single control in its Paint event instead. It should be a lot quicker than creating general purpose controls such as PictureBoxes.


这篇关于任务parallel.invoke()上的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆