任务是阻止 UI 而不是返回字符串

Task is block the UI instead of returing a string

我有一个网络表单:当我单击一个按钮时,它会调用一个调用网络服务的方法,但在网络调用执行后,该方法不会返回字符串并且 UI 会不断加载。

网络表单代码如下所示:

Task<string> result = TheWebService.SendWebRequest();
Output.Text = result.Result; //an aspx Literal control

Web 服务代码如下所示:

public async Task<string> SendWebRequest()
{       
   response = await client.PostAsync(request);

   if (response.IsSuccessStatusCode)
   {
     return "1";
   }
   else
   {
     return "2";
    }
}

Output.Text = result.Result; 永远不会执行,而是页面无休止地加载。我需要更改代码中的哪些内容才能在页面中显示结果?

Don't block on async code. Instead of Result, use async all the way.

Web 表单在这一点上是一项非常过时的技术,因此使用 async 并不是非常简单。您需要 set Page.Async to true and then register your asynchronous task using PageAsyncTask.

尝试更改您的代码,以防止死锁:

Output.Text = TheWebService.SendWebRequest().GetAwaiter().GetResult();
response = await client.PostAsync(request).ConfigureAwait(false);

但您应该知道,这只是解决方法。代码同步运行。