我正在为朋友的生日申请,应该会弹出一个带有不断变化的赞美的窗口。但是,窗口会冻结,并且标签不会更改。我用谷歌搜索了它,并阅读了一些关于使用 Backgroundworker 的内容,以便将 GUI 线程与不断变化的进程分开。还是不行。
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
namespace ProjectL
{
public partial class Form1 : Form
{
private MessageHandler theHandler = new MessageHandler();
private BackgroundWorker theBackgroundWorker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
}
private void StartButton_Click(object sender, EventArgs e)
{
StartButton.Visible = false;
theBackgroundWorker.DoWork += new DoWorkEventHandler(theBackgroundWorker_doYourWork);
//theBackgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(theBackgroundWorker_doYourWork);
theBackgroundWorker.RunWorkerAsync();
theHandler.RunMessage(hBDLabel, youAreLabel, mainLabel, this);
}
void theBackgroundWorker_doYourWork(object sender, DoWorkEventArgs e)
{
theHandler.RunMessage(hBDLabel, youAreLabel, mainLabel, this);
}
}
}
这是应该在后台发生的事情,使用我命名为 MessageHandler 的类:
class MessageHandler
{
public List<String> GenerateComplimentTexts()
{
List<String> stringList = new List<String>();
//Adding a bunch of compliments into a List<String>
return stringList;
}
public void RunMessage(Label hBDLabel, Label youAreLabel, Label mainLabel, Form1 form)
{
List<String> stringList = GenerateComplimentTexts();
Thread.Sleep(2000);
form.Text = "Happy Birthday Goose!!!";
hBDLabel.Text = "Happy Birthday Goose!";
Thread.Sleep(3000);
youAreLabel.Text = "You are...";
Thread.Sleep(2000);
foreach (String e in stringList)
{
mainLabel.Text = e;
//form.Test = e
Thread.Sleep(1000);
}
Thread.Sleep(3000);
mainLabel.Text = "";
youAreLabel.Text = FinalMessage;
}
private String _finalMessage = "FINAL MESSAGE";
public String FinalMessage {get {return _finalMessage;}}
}
尽管如此,我的窗户上没有任何变化。如果我选择取消注释 form.Text = e; ,除了表单本身顶部栏中的文本外,一切都几乎被冻结了。
有什么建议吗?