c# - WPF application crashes when using System.Threading.Thread -


i have button named submit_button has following code in onclicked event:

    thread thread = new thread(new threadstart(heavywork));     thread.start(); 

heavywork function code :

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 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; } 

when run application, press button, application crashes immediately!

what's happening ? tried use backgroundworker instead, when can worker.runworkerasync() nothing happens ( worker doesn't start ).

you going want ui related stuff on ui thread, can dispatcher, so:

private void heavywork() {     application.current.dispatcher.invoke(dispatcherpriority.normal, new action(disableui));     //rest of method     application.current.dispatcher.invoke(dispatcherpriority.normal, new action(enableui)); } 

Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -