Home > Net > Help me explain what is the difference between two pieces of code
Help me explain what is the difference between two pieces of code
Time:10-06
Getting stuck in the first paragraph, in the form of form threads, unable to get the results
public async Task The Test (string url) { Try { Var webclient=new webclient (); Var res=await webclient. DownloadStringTaskAsync (url); return res; } The catch (Exception e) {
Throw new Exception (e.M essage); }
}
Private void Button1_Click (object sender, EventArgs e) { Var dd=Test (" http://127.0.0.1:5000/swagger/v1/swagger.json "). The Result; Console. WriteLine (dd); }
The second section, can be obtained in the form as a result, but I don't understand why do
Public async Task The Test (string url) { Try { Var webclient=new webclient (); Var res=await webclient. DownloadStringTaskAsync (url); return res; } The catch (Exception e) {
Throw new Exception (e.M essage); }
}
Private void Button1_Click (object sender, EventArgs e) { Var dd=Task. Run (()=& gt; Test (" http://127.0.0.1:5000/swagger/v1/swagger.json "). The Result; Console. WriteLine (dd); }
CodePudding user response:
. The Result; This is synchronized code
As for the second to tell the truth, at odds, if compared to the following code
private async void Button1_Click (object sender, EventArgs e) { Var dd=await Test (" http://127.0.0.1:5000/swagger/v1/swagger.json ")); Console. WriteLine (dd); }
CodePudding user response:
The first cause "deadlock", because in the synchronization method calls the asynchronous, the Test Result of the Button1_Click thread A over, to be performed for execution after await the return of the operation, and thread A waiting for the Result also return A Result, leads to both of them at the same time to wait, should avoid to use the Result attribute, internal calls A wait operation, in, in the netcore does not exist in the deadlock problem, because await execution may be on A different thread,
The second use of the Task. Run the test execution method, which is not in the performance of the Button1_Click thread A, but from another thread, also won't have to wait for A complete, but this will happen A context switch, leading to loss of some information in the current context, may also cause some UI controls appear abnormal operation, because there are already across threads operation error, it will output the dd values immediately,
For the first kind of circumstance, can be amended as: await webclient. DownloadStringTaskAsync (url) . ConfigureAwait (false) ; To resume execution on other threads, await,