[英]Calling Async methods in Page_Load asp c#
嗨,我是異步使用async和await的新手,並且我希望將在page_load
中發生的一些調用作為異步調用。
這是代碼。
protected void Page_Load(object sender, EventArgs e)
{
string UrlData = ReadAsync().Result;
//continuation code..
}
protected async Task<string> ReadAsync(object sender, EventArgs e)
{
Task<string> T = getFinalValue();
await T;
return T.Result;
}
protected async Task<string> getFinalValue(object sender, EventArgs e)
{
//my code to create string
return "created string";
}
和
1.我需要了解這是正確的方法嗎?
2.使用ReadAsync().Result
synchronous方法中的ReadAsync().Result
是否正確或導致任何其他問題?
3.我是否需要在兩者之間使用ReadAsync
方法來解決這個問題,還是可以在page_load
直接使用getFinalValue
以及如何使用它?
4,我可以將page_load
保持為同步還是異步? 哪個更好的方法?
任何回應都會有所幫助。
經典的ASP.NET在異步方面並不能很好地發揮作用,您需要將其更改為類似...
protected void Page_Load(object sender, EventArgs e)
{
RegisterAsyncTask(new PageAsyncTask(ReadAsync));
}
protected async Task ReadAsync()
{
string UrlData = await getFinalValue();
//continuation code..
}
protected async Task<string> getFinalValue()
{
//my code to create string
return "created string";
}
請參閱Scott Hanselman關於該主題的文章...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.