Quote:
public async void PopulateAdditionalStaffEmailListBox()
You've found one of the many reasons to
avoid async void
methods[
^]. :)
Your
Page_Load
event handler calls
PopulateAdditionalStaffEmailListBox
. That method gets as far as the first
await
statement and returns.
The calling code has no way of knowing that the method has not completed yet, so it continues to run. The page is rendered and the content is sent back to the user - without any values in the list.
At some later point, the
await
completes, and the rest of the
PopulateAdditionalStaffEmailListBox
method runs. But it's too late - the response has already been sent back to the client. Anything you add to the list now will simply be thrown away.
There are a couple of ways to solve this. Both will require that you add
Async="True"
to your
<%@ Page %>
directive. And both will require that you change your
PopulateAdditionalStaffEmailListBox
method to return a
Task
.
Option 1:
Use
the RegisterAsyncTask
method[
^]:
public async Task PopulateAdditionalStaffEmailListBox() { ... }
public void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Page.RegisterAsyncTask(new PageAsyncTask(PopulateAdditionalStaffEmailListBox));
}
}
Option 2:
Use
async model binding[
^]
(requires .NET 4.6 or later):
public async Task<IEnumerable<GetRequestorInfoModel>> GetAdditionalStaffEmails()
{
var staffEmails = await FTACaseReseting.Controllers.RequestorInfoController.GetAllRequestorInfoes();
return staffEmails.OrderBy(x => x.DisplayName);
}
Markup:
<asp:ListBox ID="AdditionalStaffEmailListBox" runat="server"
SelectMethod="GetAdditionalStaffEmails"
DataTextField="DisplayName"
DataValueField="Email"
/>
Using Asynchronous Methods in ASP.NET 4.5 | Microsoft Docs[
^]