C#4.0从Parallel.ForEach中访问表单控件

84R*_*73R 2 c# parallel-processing winforms

下面的代码运行正常.我想知道它是否真的正确?

if (openFileDialog.ShowDialog() == DialogResult.OK)
{
    Parallel.ForEach(openFileDialog.FileNames, currentFile =>
    {
       try
       {
           StreamReader FileReader = new StreamReader(currentFile);
           do
           {
               URLtextBox.Invoke(new MethodInvoker(delegate
               {
                   URLtextBox.Text += SelectURLfromString(FileReader.ReadLine());
               }));
           }
           while (FileReader.Peek() != -1);
           FileReader.Close();
        }
        catch (System.Security.SecurityException ex)
        {
            ...
        }
        catch (Exception ex)
        {
            ...
        }
     });
}
Run Code Online (Sandbox Code Playgroud)

否则我得到"跨线程操作无效.控制'URLtextBox'从另一个线程访问"或卡住应用程序.

Fem*_*ref 5

代码是正确的 - 您需要使用Invoke从GUI线程外部刷新控件.但是,您也在SelectURLfromString(FileReader.ReadLine());GUI线程中删除了该方法,您应该将其替换为

   string url = SelectURLfromString(FileReader.ReadLine());
   URLtextBox.Invoke(new MethodInvoker(delegate
   {
       URLtextBox.Text += url;
   }));
Run Code Online (Sandbox Code Playgroud)

尽量减少GUI线程中的工作.