英文:
Error when converting a synchronous method to an asynchronous method
问题
以下是代码的翻译部分:
public static async Task<List<Employee>> EmployeesList()
{
List<Employee> list = new List<Employee>();
DataTable dt = new DataTable();
dt = await Data.DataAccess.ExecuteDataTableAsync("[Employee].[dbo].[Employee_Select]");
foreach (DataRow row in dt.Rows)
{
list.Add(new Employee()
{
Id = Convert.ToInt32(row["ID"]),
Name = Convert.ToString(row["Name"]),
Email = Convert.ToString(row["Email"]),
Age = Convert.ToInt32(row["Age"]),
Salary = Convert.ToInt32(row["Salary"])
});
}
return list;
}
请注意,已经将原始代码转换为异步方法。
英文:
I am trying to convert this block of code to Async
public static List<Employee> EmployeesList()
{
List<Employee> list = new List<Employee>();
DataTable dt = new DataTable();
dt = Data.DataAccess.ExecuteDataTable("[Employee].[dbo].[Employee_Select]");
foreach (DataRow row in dt.Rows)
{
list.Add(new Employee()
{
Id = Convert.ToInt32(row["ID"]),
Name = Convert.ToString(row["Name"]),
Email = Convert.ToString(row["Email"]),
Age = Convert.ToInt32(row["Age"]),
Salary = Convert.ToInt32(row["Salary"])
});
}
return list;
}
The modified code looks like this
public static async Task<List<Employee>> EmployeesList()
{
List<Employee> list = new List<Employee>();
DataTable dt = new DataTable();
dt = await Data.DataAccess.ExecuteDataTableAsync("[Employee].[dbo].[Employee_Select]");
foreach (DataRow row in dt.Rows)
{
list.Add(new Employee()
{
Id = Convert.ToInt32(row["ID"]),
Name = Convert.ToString(row["Name"]),
Email = Convert.ToString(row["Email"]),
Age = Convert.ToInt32(row["Age"]),
Salary = Convert.ToInt32(row["Salary"])
});
}
return list;
}
Edit for clarity. The synchronous method returns a list. The asynchronous method does not (It just exits the block and skipping the break points under the await), which causes a null reference error further down the path. Why isn't my Asynchronous method returning any results?
Ignore this part from the original post.
The problem I am having is that my async code block seems to be exiting before the data is returned because the Razor page gives me an Object reference not set to an instance of an object error on my Model.Employees. What am I doing wrong?
答案1
得分: 1
什么是调用此方法的代码?
一旦进入异步\等待,您需要等待所有调用方法。
您需要等待EmployeeList()。否则,调用方法会过早放弃控制,而您的列表始终为null。
希望这有帮助
英文:
What is your calling code to this method?
Once you enter into async\await, you need to await all the calling methods.
You need to await EmployeeList(). Otherwise the calling method prematurely given control and your list is always null.
Hope this helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论