【问题标题】:Calling Async methods in Page_Load asp c#在Page_Load asp c#中调用异步方法
【发布时间】:2017-05-09 12:06:42
【问题描述】:

您好,我不熟悉在异步方法中使用 asyncawait, 我想将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是正确的还是会导致任何其他问题?

3.我是否需要在两者之间使用ReadAsync 方法来提供此服务,或者我可以在page_load 中直接使用getFinalValue 以及如何使用它?

4. 我可以将page_load 保持为同步或异步吗?哪个更好?

任何回应都会有所帮助。

【问题讨论】:

    标签: c# asp.net asynchronous async-await


    【解决方案1】:

    经典的 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 关于此主题的帖子...

    https://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

    【讨论】:

    • 如果我想从ReadAsync 将字符串返回到 void 怎么办?
    • 我不确定这是否可行。在经典的 ASP.NET Web 表单应用程序中使用异步有一些相当大的限制
    • 对不起,我不知道关于这个主题的好信息。我认为 ASP.NET Web 表单中对异步的支持有限,而 MVC/Web API 的支持要好得多。
    猜你喜欢
    • 2016-03-16
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 1970-01-01
    • 2015-11-09
    相关资源
    最近更新 更多