我有一个名为 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()
时什么也没有发生(工作人员没有启动)。
最佳答案
DisableUI() 在非 UI 线程的线程上更改 UI 控件的状态。这在 WPF 中是不允许的,因为它是一个 single threaded UI framework。 ,并且只允许您更改对称为 UI 线程的控件的控制。 Dispatcher.Invoke()/BeginInvoke() 是你的 friend 。
关于c# - 使用 System.Threading.Thread 时 WPF 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18121938/