2

我有一个名为的按钮,它在OnClicked事件submit_Button中具有以下代码:

    Thread thread = new Thread(new ThreadStart(heavyWork));
    thread.Start();

重工功能代码:

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()没有发生时(工人没有启动)。

4

3 回答 3

3

DisableUI() 正在更改不是 UI 线程的线程上的 UI 控件的状态。这在 WPF 中是不允许的,因为它是一个单线程 UI 框架,并且只允许您更改称为 UI 线程的控件。Dispatcher.Invoke()/BeginInvoke() 是你的朋友。

关于使用 Dispatcher 的优秀 MSDN 文章

于 2013-08-08T09:05:29.620 回答
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));
}
于 2013-08-08T09:08:01.253 回答
1

使用 Background Worker 时,您的代码应如下所示: 请注意,当您启动worker.RunWorkerAsync()方法时,会调用 BackgroundWorkerDoWork

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
}
于 2013-08-08T09:08:32.820 回答