c# - 使用 System.Threading.Thread 时 WPF 应用程序崩溃

标签 c# wpf multithreading backgroundworker

我有一个名为 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 。

Good MSDN article on using the Dispatcher

关于c# - 使用 System.Threading.Thread 时 WPF 应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18121938/

相关文章:

android - 在 ListView 项目按钮单击时需要有关 AsyncTask 的帮助

c# - 使用 CodeDom 从外部类调用方法

c# - 拖放形状

c# - Saga 等待状态值

c# - 无法找到 'app.xaml',IOException 直到修改 app.xaml

c# - 在 .NET 应用程序中播放视频

c - 双缓冲设计I/O同步

python - 在 numba 中使用多线程

c# - 在 ASP.Net MVC Core 中创建新 Controller 时,如何防止 MVC Core 添加一些不需要的包?

c# - 让 GetDecimal 发挥作用