0
private void timer1_Tick(object sender, EventArgs e)
{        
   string[] DF_Engines = { Form2.Engine1, Form2.Engine2, Form2.Engine3, Form2.Engine4, Form2.Engine5, Form2.Engine6 };
   foreach (string DF_Engine in DF_Engines)
   {
       if (Convert.ToDouble(DF_Engine) != 99)
       {
           string Hex_ADD1 = "{" + DF_Engine + "|";
           Console.WriteLine(Hex_ADD1);
           serialPort1.Write(Hex_ADD1);
           n = Convert.ToInt16(DF_Engine);               
        }
    }
}

Form2.Engine1, Form2.Engine2.......Form2是选中相应复选框时的值。这些将是 1, 2 , 3 等等....我的代码在选择 checkbox1 时发送 01,但是当在 Form2 中选择 checkbox1 和 checkbox2 时它会毫无延迟地发送 01,02。根据我的兴趣,我在询问 01 和 02 等时需要延迟。我怎么能做到这一点,当我使用时Thread.Sleep(500),应用程序变慢了。需要指导。

4

2 回答 2

0

您可以考虑使用一个单独的线程,只是一个BackgroundWorker控件。这样,您可以使用Thread.Sleep()方法并且它不应该使应用程序的 GUI 无响应。您可以在 msdn 上找到有关它的更多信息:http: //msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx

只需在表单中添加一个BackgroundWorker控件并使用此代码来处理适当的事件:

private void timer1_Tick(object sender, EventArgs e)
{
    string[] DF_Engines = { Form2.Engine1, Form2.Engine2, Form2.Engine3, Form2.Engine4, Form2.Engine5, Form2.Engine6 };

    //disable timer1, so it wont tick again until the current work is finished
    timer1.Stop();

    //start processing asynchronously, so GUI is still responsive
    sampleBackgroundWorker.RunWorkerAsync(DF_Engines);
}

//this method should be attached to DoWork event of the BackgroundWorker
private void sampleBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    string[] DF_Engines = (e.Argument as string[]);

    foreach (string DF_Engine in DF_Engines)
    {
        if (Convert.ToDouble(DF_Engine) != 99)
        {
            string Hex_ADD1 = "{" + DF_Engine + "|";
            Console.WriteLine(Hex_ADD1);
            serialPort1.Write(Hex_ADD1);
            //n gets overwritten in each iteration, is this line required?
            n = Convert.ToInt16(DF_Engine);

            Thread.Sleep(500);
        }
    }

    //you can also pass a result from this method back to the GUI thread like this
    //e.Result = "job done";
    //this can be read later in RunWorkerCompleted method of the BackgroundWorker
}

//this method should be attached to RunWorkerCompleted event of the BackgroundWorker
private void sampleBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    //start timer1, so it can invoke the worker again
    timer1.Start();
}

如果您需要更多帮助,请告诉我。

于 2012-08-04T07:02:53.060 回答
0

不要在 UI 线程上使用 Thread.Sleep。它肯定会减慢您的应用程序。而是启动一个新线程,将数据传递给该线程并让该线程延迟将输入发送到您的应用程序。

System.Threading.Thread thread = new System.Threading.Thread((inputList) =>
    {
       foreach (var input in inputList as IEnumerable<int>)
       {
          //Send input
          System.Threading.Thread.Sleep(500);
        }
      });
  thread.Start();

其中 inputList 是一个数据数组(1,2 等,具体取决于您选择的复选框)。

于 2012-08-04T07:03:42.490 回答