如何添加/插入多线程运行或执行在WinForm(请参阅我的代码)

本文关键字:WinForm 执行 请参阅 代码 我的 多线程 何添加 添加 插入 运行 | 更新日期: 2023-09-27 17:52:47

当我运行代码并单击执行按钮时,它在运行时挂起(特别是当我运行更多文件时),我不能再单击我的主表单,它需要在与我的主表单交互之前先完成我的执行。我研究了我需要多线程。我将如何插入多线程或后台工作人员的代码,使我仍然可以与我的表单交互。

下面是执行按钮,当我点击它时,开始执行我的脚本,并在未完成时冻结我的表单。

    private void Execute_Click(object sender, EventArgs e)
    {
        try
        {                
            //Execution Pane
            timer1.Start();
            progressBar1.Maximum = checkedListBox1.CheckedItems.Count;
            richTextBox2.Text = "";
            string file_name = "''test1.sql";
            file_name = textBox1.Text + file_name;
            {                 
                string line;
                line = null;
                foreach (Object item in checkedListBox1.CheckedItems)
                {
                    string sql_name = "''test1.sql";
                    sql_name = textBox1.Text + sql_name;
                    StreamWriter SaveFile = new StreamWriter(sql_name);
                    SaveFile.WriteLine(":r '"" + textBox1.Text + "''" + item + "'"");
                    SaveFile.Close();
                    line += item + "'n";
                    StreamReader sql = new StreamReader(sql_name);
                    //richTextBox1.Text = sr.ReadToEnd();
                    sql.Close();
                    sql.Dispose();
                    //Create a batchfile for execution of consolidated script 
                    string execute = "''Script_Runner.bat";
                    execute = textBox1.Text + execute;
                    StreamWriter SaveFile2 = new StreamWriter(execute);
                    SaveFile2.WriteLine("sqlcmd -S localhost -E -i " + textBox1.Text + "''" + "test1.sql");
                    //Environment.NewLine + "pause");
                    SaveFile2.Close();
                    //running the batchfile
                    string ScriptRun = "''Script_Runner.bat";
                    ScriptRun = textBox1.Text + ScriptRun;
                    Process.Start(ScriptRun);
                    progressBar1.PerformStep();
                    this.Refresh();
                }
                richTextBox2.Text = line;
                richTextBox2.Text += "'nData Patch Completed.";
                transfer = label3.Text;
                NotificationForm NF = new NotificationForm();
                NF.Show();
            }
        }
        catch (Exception ex)
        {
            string filePath = @"C:'Error.txt";
            filePath = textBox1.Text + filePath;
            using (StreamWriter writer = new StreamWriter(filePath, false))
            {
                writer.WriteLine("Message :" + ex.Message + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                   "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
                writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
            }
        }
    }                   

如何添加/插入多线程运行或执行在WinForm(请参阅我的代码)

将BackgroundWorker拖放到表单中,在Execute_Click事件中添加以下代码。

  try
  {
    BackgroundWorker1.RunWorkerAsync() ;
  }   
  catch
  {
    BackgroundWorker1.WorkerSupportsCancellation = True
    BackgroundWorker1.CancelAsync()
  }

添加Do_Work事件到你的后台工作者。

  private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  {
        //You need to add CheckForIllegalCrossThreadCalls to allow
        BackgroundWorker access the objects you used in the form.
        Label.CheckForIllegalCrossThreadCalls = false;
        ProgressBar.CheckForIllegalCrossThreadCalls = false;
        RichTextBox.CheckForIllegalCrossThreadCalls = false;
        TextBox.CheckForIllegalCrossThreadCalls = false;
        try
    {                
        //Execution Pane
        timer1.Start();
        progressBar1.Maximum = checkedListBox1.CheckedItems.Count;
        richTextBox2.Text = "";
        string file_name = "''test1.sql";
        file_name = textBox1.Text + file_name;
        {                 
            string line;
            line = null;
            foreach (Object item in checkedListBox1.CheckedItems)
            {
                string sql_name = "''test1.sql";
                sql_name = textBox1.Text + sql_name;
                StreamWriter SaveFile = new StreamWriter(sql_name);
                SaveFile.WriteLine(":r '"" + textBox1.Text + "''" + item + "'"");
                SaveFile.Close();
                line += item + "'n";
                StreamReader sql = new StreamReader(sql_name);
                //richTextBox1.Text = sr.ReadToEnd();
                sql.Close();
                sql.Dispose();
                //Create a batchfile for execution of consolidated script 
                string execute = "''Script_Runner.bat";
                execute = textBox1.Text + execute;
                StreamWriter SaveFile2 = new StreamWriter(execute);
                SaveFile2.WriteLine("sqlcmd -S localhost -E -i " + textBox1.Text + "''" + "test1.sql");
                //Environment.NewLine + "pause");
                SaveFile2.Close();
                //running the batchfile
                string ScriptRun = "''Script_Runner.bat";
                ScriptRun = textBox1.Text + ScriptRun;
                Process.Start(ScriptRun);
                progressBar1.PerformStep();
                this.Refresh();
            }
            richTextBox2.Text = line;
            richTextBox2.Text += "'nData Patch Completed.";
            transfer = label3.Text;
            NotificationForm NF = new NotificationForm();
            NF.Show();
        }
    }
    catch (Exception ex)
    {
        string filePath = @"C:'Error.txt";
        filePath = textBox1.Text + filePath;
        using (StreamWriter writer = new StreamWriter(filePath, false))
        {
            writer.WriteLine("Message :" + ex.Message + Environment.NewLine + "StackTrace :" + ex.StackTrace +
               "" + Environment.NewLine + "Date :" + DateTime.Now.ToString());
            writer.WriteLine(Environment.NewLine + "-----------------------------------------------------------------------------" + Environment.NewLine);
        }
    }
  }
private void Execute_Click(object sender, EventArgs e)
{
  Task.Factory.StartNew(() =>
  {
    if (InvokeRequired)
    {
      Invoke(new MethodInvoker(DoSomething));
    }
    else
    {
      DoSomething();
    }
  });
}
private void DoSomething()
{
  try
  {
    //Execution Pane
    timer1.Start();
    progressBar1.Maximum = checkedListBox1.CheckedItems.Count;
    richTextBox2.Text = "";
    var file_name = "''test1.sql";
    file_name = textBox1.Text + file_name;
    {
      string line;
      line = null;
      foreach (var item in checkedListBox1.CheckedItems)
      {
        var sql_name = "''test1.sql";
        sql_name = textBox1.Text + sql_name;
        var SaveFile = new StreamWriter(sql_name);
        SaveFile.WriteLine(":r '"" + textBox1.Text + "''" + item + "'"");
        SaveFile.Close();
        line += item + "'n";
        var sql = new StreamReader(sql_name);
        //richTextBox1.Text = sr.ReadToEnd();
        sql.Close();
        sql.Dispose();
        //Create a batchfile for execution of consolidated script 
        var execute = "''Script_Runner.bat";
        execute = textBox1.Text + execute;
        var SaveFile2 = new StreamWriter(execute);
        SaveFile2.WriteLine("sqlcmd -S localhost -E -i " + textBox1.Text + "''" + "test1.sql");
        //Environment.NewLine + "pause");
        SaveFile2.Close();
        //running the batchfile
        var ScriptRun = "''Script_Runner.bat";
        ScriptRun = textBox1.Text + ScriptRun;
        Process.Start(ScriptRun);
        progressBar1.PerformStep();
        Refresh();
      }
      richTextBox2.Text = line;
      richTextBox2.Text += "'nData Patch Completed.";
      var transfer = label3.Text;
      //NotificationForm NF = new NotificationForm();
      //NF.Show();
    }
  }
  catch (Exception ex)
  {
    var filePath = @"C:'Error.txt";
    filePath = textBox1.Text + filePath;
    using (var writer = new StreamWriter(filePath, false))
    {
      writer.WriteLine("Message :" + ex.Message + Environment.NewLine + "StackTrace :" + ex.StackTrace +
                        "" + Environment.NewLine + "Date :" + DateTime.Now);
      writer.WriteLine(Environment.NewLine +
                        "-----------------------------------------------------------------------------" +
                        Environment.NewLine);
    }
  }
}