Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 由于button.performClick()的原因,跨线程操作无效_C#_.net_Multithreading_Exception Handling_Thread Safety - Fatal编程技术网

C# 由于button.performClick()的原因,跨线程操作无效

C# 由于button.performClick()的原因,跨线程操作无效,c#,.net,multithreading,exception-handling,thread-safety,C#,.net,Multithreading,Exception Handling,Thread Safety,您好,我正在研究一个禁忌搜索算法,我需要访问许多函数以使其可读性和易用性。我使用了按钮和button.performClick() 有人能告诉我我做错了什么,以及我如何解决这个问题吗? 多谢各位 struct DataParameter { public int Process; public int Delay; } private DataParameter _inputparameter; private void

您好,我正在研究一个禁忌搜索算法,我需要访问许多函数以使其可读性和易用性。我使用了按钮和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();
        }
    }

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

DateTime timeout=DateTime.Now.add毫秒(50);
while(DateTime.Now
它应该会起作用


祝你好运

请查看的指南。特别是-正在发生的事情与你期望发生的事情。你收到错误信息了吗?如果是,是什么?什么是
按钮。performClick
-它不会出现在您的代码中?此外,这很可能是的重复-这是一个非常常见的问题…不要尝试在
DoWork
中显示消息框。此方法在与UI线程不同的线程上执行。传递信息并处理
RunWorkerCompleted
事件中的错误,该错误将在UI线程上执行。当您在单击处理程序中测试它只应在backgroundworker未运行时执行某项操作时,为什么要从DoWork调用cmd\u Start\u Scheduling.PerformClick()?看起来很荒谬。因为那个按钮连接到一个函数,为什么我得到了-1?我只是在帮助那个家伙,这可能不是最好的答案,但它works@TimJones如果你知道这是一个糟糕的答案,那么你为什么要把它放在首位?如果你知道一个答案是错误的,而你却得到了反对票,那你为什么会感到惊讶呢?你刚刚带领OP走上了一条可能会给他带来更多问题的道路,并且可能很难调试这些问题!
DateTime timeout = DateTime.Now.AddMilliseconds(50);
while (DateTime.Now < timeout) Application.doEvents;