1

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.

Peter Bons
30k4 gold badges64 silver badges83 bronze badges
asked Aug 13, 2017 at 9:07
1

1 Answer 1

3

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.

answered Aug 14, 2017 at 4:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.