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
  • 26,826
  • 4
  • 50
  • 74
Saeed Alasiry
  • 322
  • 5
  • 23
  • You should also await the Task in the event handler, `await fun()`. See also https://stackoverflow.com/questions/27282617/is-it-safe-to-use-async-await-in-asp-net-event-handlers?rq=1 about using `RegisterAsyncTask` – Peter Bons Aug 13 '17 at 11:20

1 Answers1

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.

Xiaoguo Ge
  • 2,177
  • 20
  • 26