无限的循环崩溃

时间:2015-08-12 04:06:52

标签: c# winforms

这里我有一个包含两个项目的Windows应用程序:

RichTextBox chatbot

按钮startButton

好的,所以当按下开始按钮时,一些代码会运行,然后它会响应这个循环:

for( i in unique(cdata$temp)) {
 i<- cdata[cdata$temp== i,]
 my.plot<-qplot(i$Year,
   i$Consumption,
   main =paste0("Consumption  ", prettyNum(i, ",")),
   xlab = "Year",
   ylab = "Consumption (kcal)")
+scale_x_continuous(breaks =paste0(seq(2010, 2100, by=10))))

print(my.plot)
}

轰隆隆...程序停止响应...

当我在控制台程序中运行此代码时,尽管它都是有效的。运行良好,执行良好,按预期执行。

这段代码除了(Twitch Bot我正在制作)

1 个答案:

答案 0 :(得分:1)

我认为您必须使用BackgroundWorker来避免UI卡住。

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
}

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender,            System.ComponentModel.DoWorkEventArgs e)
{
     // Your infinite loop here, example is given below
     for (int i = 0; i < 100000; i++)
     {
        Console.WriteLine(i);
         Thread.Sleep(1000);
     }
}