multithreading - C# Async/Await and HttpClient with UI update -


so i'm making post request website , told best way using httpclient asynchronously.

i used this guide , implemented on form's file. problem need update ui basic label text change , buttons/textboxes disabling.

it worked fine @ first noticed postasync(...) task "hang" stop (at least, console shows thread stopped after time) , code after post call wouldn't execute, resulting in unusable interface since froze buttons.

after research added configureawait(false) @ end of request, resulted in targetinvocationexception (innerexception tells me couldn't update label because of inter-thread operation) stopped there.

here's code have:

public async void dostuff()         {             //ui locking             textbox1.enabled = false;             textbox2.enabled = false;             button2.enabled = false;             label4.text = "request in progress ...";             label4.forecolor = color.orangered;              //post params             var postparams = new dictionary<string, string>             {                 {"username", textbox1.text },                 {"password", textbox2.text },             };              //setting httpclient post & ua             var content = new formurlencodedcontent(postparams);             client.defaultrequestheaders.add("user-agent", "mozilla/5.0 (windows nt 6.1; win64; x64; rv:55.0) gecko/20100101 firefox/55.0");              //actual request             var response = await client.postasync("http://example.com", content).configureawait(false);             var responsestring = await response.content.readasstringasync();              if (responsestring.contains("somestuff"))             {                 label4.text = "success";                 label4.forecolor = color.limegreen;             }             else             {                 label4.text = "failed";                 label4.forecolor = color.firebrick;                 messagebox.show("username or password incorrect", "account error", messageboxbuttons.ok, messageboxicon.error);             }              //ui unlock             textbox1.enabled = true;             textbox2.enabled = true;             button2.enabled = true;         } 

could lead me right way of doing ? i'm not used c# tasks/threads i'm having hard time trying figure out.

thanks in advance !


Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -