我有一个名为submit_Button
的按钮,在 OnClicked 事件中包含以下代码:
Thread thread = new Thread(new ThreadStart(heavyWork));
thread.Start();
heavyWork 功能代码:
private void heavyWork()
{
DisableUI();
string Name = Name_textBox.Text;
celebrityName = Name.Replace(" ", "+");
string queryURL = "http://stackoverflow.com";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(queryURL);
request.Method = "GET";
// make request for web page
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader htmlSource = new StreamReader(response.GetResponseStream());
string htmlStringSource = string.Empty;
htmlStringSource = htmlSource.ReadToEnd();
response.Close();
//var regex = new Regex(@"<FONT class=""result"">(.*?)</FONT>");
var regex = new Regex(@"<span class=""kno-a-v"">(.*?)</span>");
var match = regex.Match(htmlStringSource);
var result = match.Groups[1].Value;
result = HttpUtility.HtmlDecode(result);
MessageBox.Show(result);
EnableUI();
}
// Functions
private void DisableUI()
{
celebrityName_textBox.IsEnabled = false;
submit_Button.IsEnabled = false;
infoType_listBox.IsEnabled = false;
preloader_Image.Visibility = Visibility.Visible;
}
private void EnableUI()
{
celebrityName_textBox.IsEnabled = true;
submit_Button.IsEnabled = true;
infoType_listBox.IsEnabled = true;
preloader_Image.Visibility = Visibility.Hidden;
}
当我运行应用程序,然后按下按钮时,应用程序立即崩溃!
发生了什么事?我尝试使用 BackgroundWorker ,但是当我worker.RunWorkerAsync()
没有任何反应时(工作人员无法启动)。
答案 0 :(得分:2)
DisableUI()正在更改不是UI线程的线程上的UI控件的状态。这在WPF中是不允许的,因为它是single threaded UI framework,并且只允许您更改对UI线程的控件。 Dispatcher.Invoke()/ BeginInvoke()是你的朋友。
答案 1 :(得分:2)
您将要在UI线程上执行任何与UI相关的操作,您可以使用调度程序执行此操作,如下所示:
private void heavyWork()
{
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(DisableUI));
//rest of method
Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(EnableUI));
}
答案 2 :(得分:1)
使用Background Worker时,您的代码应如下所示: 请注意,当您启动 worker.RunWorkerAsync()方法时,会调用BackgroundWorker Do Work
BackgroundWorker _backgroundWorker = new BackgroundWorker
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true
};
_backgroundWorker.DoWork += BackgroundWorkerDoWork;
_backgroundWorker.RunWorkerCompleted += BackgroundWorkerRunWorkerCompleted;
void BackgroundWorkerDoWork(object sender, DoWorkEventArgs e)
{
//DU STUFF HERE
}
void BackgroundWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
/DO STUFF HERE LIKE HIDE / SHOW / ENABLE/ DISABLE buttons
}