如何在多线程应用程序中正确使用委托

时间:2019-03-04 09:25:38

标签: c# multithreading delegates

我正在尝试在表单顶部显示一个消息框并获取结果。我正在使用backgroundworker,在我的dowork函数中,我正在调用以下函数。我根据过去的经验使用了代表来显示消息框,但是我不确定是什么错误使我误入了错误。

  

e.Message =“跨线程操作无效:控件'Form1'   从创建该线程的线程以外的线程访问。”

您介意检查为什么即使在使用委托后我仍然遇到上述错误吗?

        public delegate DialogResult Del(Form1 fr,string text, string title, MessageBoxButtons mbb, MessageBoxIcon mbi);

        public static DialogResult showMessageBox(Form1 fr, string text, string title, MessageBoxButtons mbb, MessageBoxIcon mbi)
        {
            return MessageBox.Show(fr, text, title, mbb, mbi);
        }



  public static OutputEventArgs execSync(string exe, string arguments, string standardInput,Form1 fr)
        {
            OutputEventArgs oea = new OutputEventArgs();
            try
            {
                using (Process myProcess = new Process())
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    startInfo.RedirectStandardOutput = true;
                    startInfo.RedirectStandardError = true;
                    startInfo.RedirectStandardInput = true;
                    startInfo.UseShellExecute = false;
                    startInfo.CreateNoWindow = true;

                    startInfo.FileName = exe;
                    startInfo.Arguments = arguments;
                    myProcess.StartInfo = startInfo;

                    myProcess.Start();
                    string line = string.Empty;

                    while (!myProcess.StandardOutput.EndOfStream)
                    {
                        line = myProcess.StandardOutput.ReadLine();
                        if (line.Contains("is already defined in archive"))
                        {
                            Del handler = new Del(showMessageBox);

                            DialogResult dialogResult = handler(fr, "Do you want overwrite the version label?", "OverWrite",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
                            if(dialogResult == DialogResult.Yes)
                                myProcess.StandardInput.WriteLine("y");
                            else
                                myProcess.StandardInput.WriteLine("n");
                        }

                    }

                    oea.Data = line;

                    myProcess.WaitForExit();
                    oea.exitCode = myProcess.ExitCode;
                }
            }
            catch (Exception e)
            {
                oea.Data = e.Message;
                oea.ExceptionHappened();
            }
            return oea;
        }

0 个答案:

没有答案