由于button.performClick(),跨线程操作无效

时间:2017-02-28 12:26:15

标签: c# .net multithreading exception-handling thread-safety

您好我正在研究TABU搜索算法,我需要访问许多函数以使其易读且易于使用按钮和button.performClick();

有人能让我知道我做错了什么以及如何解决这个问题? 谢谢

    struct DataParameter
    {
        public int Process;
        public int Delay;
    }
    private DataParameter _inputparameter;

    private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        progressBar1.Value = e.ProgressPercentage;
        lblBackGroundWorker.Text = string.Format("Processing...{0}%", e.ProgressPercentage);
        progressBar1.Update();
    }

    private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        int process = ((DataParameter)e.Argument).Process;
        int delay = ((DataParameter)e.Argument).Delay;
        int index = 1;
        try
        {
            //progressBar1.Value = 0;
            //progressBar1.Update();
            progressBar = 1;
            //this.tmrTimeAndDate.Start();
            Reset_Clear_For_New_Timetable();
            sw_WhileLoop = Stopwatch.StartNew();
            while (whileLoop > 0)
            {
                if (!backgroundWorker.CancellationPending)
                {
                    backgroundWorker.ReportProgress(index++ * 100 / process, string.Format("Processing...{0}%", progressBar));
                    Thread.Sleep(delay); // used to simulate length of operation

                    if (whileLoop == 99)
                    {

                        Console.WriteLine("initial"); // initial
                        cmd_Start_Scheduling.PerformClick(); // create timetable
                        Get_Timetable_Send_To_Initial_DataTable(); // get timetable to the initial table
                        Get_Timetable_Send_To_Optimal_DataTable(); // get timetable to the optimal table
                        Calculate_Energy_High_Score_Initial();//calculate high score of initial solution
                        Calculate_Energy_High_Score_Optimal();//calculate high score of optimal solution
                        Reset_Clear_For_New_Timetable();

                    }
                    else
                    {
                        Console.WriteLine("not initial");// not initial
                        cmd_Start_Scheduling.PerformClick(); // create timetable
                        Fill_New_Solution();
                        Compare_Solution_Keep_The_Best();
                        Reset_Clear_For_New_Timetable();
                    }

                    whileLoop = whileLoop - 1;
                    progressBar = progressBar + 1;


                }
            }
            sw_WhileLoop.Stop();
            MessageBox.Show("Time taken: " + sw_WhileLoop.Elapsed.TotalSeconds.ToString() + " seconds \n Scheduling ended on step 7 because there was no Sup Class Left.");
            MessageBox.Show("Done");
            TimetableOutputQuestion TimetableOutputQuestionOpen = new TimetableOutputQuestion();
            this.Hide();
            TimetableOutputQuestionOpen.Show();
            progressBar = 1;
            whileLoop = 99;

        }
        catch (Exception ex)
        {
            backgroundWorker.CancelAsync();
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        MessageBox.Show("Timetable Scheduling Process Has Been Completed", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    private void CmdStartScheduling_Click(object sender, EventArgs e)
    {
        if (!backgroundWorker.IsBusy)
        {
            _inputparameter.Delay = 100;
            _inputparameter.Process = 1200;
            backgroundWorker.RunWorkerAsync(_inputparameter);
        }
    }

    private void cmdStopScheduling_Click(object sender, EventArgs e)
    {
        if (backgroundWorker.IsBusy)
        {
            backgroundWorker.CancelAsync();
        }
    }

1 个答案:

答案 0 :(得分:-2)

将此代码添加到while循环的末尾(循环内部)

DateTime timeout = DateTime.Now.AddMilliseconds(50);
while (DateTime.Now < timeout) Application.doEvents;

它应该可以解决问题。

祝你好运