I am so confusing about using asynch
with webform
, I make onClick function for button in asp.net server side, and inside this function I make another function this function is asynch
and return type of it Task<int>
, in side this function I put Task.Run
which run some code and I use await with it, after await finishing I want to change label text in my UI but after finish await there is no thing happen in UI
Code of click button:
protected void btn_click(object sender , EventArgs e)
{
fun();
}
Code of asynch function:
public asynch Task<int> fun()
{
Task<String> s = Task.Run(()=>someCodeTakeTime());
await s;
lable.Text = "finish";
return 1;
}
I know it is not recommended to using Task.Run
in side asynch
, and my code not make useful job, but I want to know from it how asynch
function works exactly.
1 Answer 1
The handler function btn_click() is defined as void. As far as ASP.NET is concerned, when this function exists, the handler function is considered finished and complete. ASP.NET will send the response to the browser right away. It has no knowledge of anything happening inside fun(), which actually created a task and queued it for execution.
In order for this to work, btn_click has to be written as
protected async Task btn_click(object sender , EventArgs e)
{
await fun();
}
The return type of Task tells ASP.Net that its execution result will be in the task. You should wait for that task to finish, grab its result, and send a response to the browser according to the result.
Comments
Explore related questions
See similar questions with these tags.
await fun()
. See also stackoverflow.com/questions/27282617/… about usingRegisterAsyncTask