【问题标题】:How to get async value from string method如何从字符串方法中获取异步值
【发布时间】:2021-01-12 22:21:09
【问题描述】:

我正在使用async 方法的API,我的代码如下,

public async void Test(string token, int tenantId, string fromDate,string searchText)
 {
    try
    {
        string serviceUrl = "http://localhost/Testapi/api/details/requestDetails/Details";

        string jsonParamterData = new JavaScriptSerializer().Serialize(new
        {
            FromDate = fromDate,
            SearchText = searchText,
        });

        HttpClient client = new HttpClient();

        HttpMethod method = new HttpMethod("POST");
        HttpRequestMessage message = new HttpRequestMessage(method, serviceUrl);

        StringContent content = new StringContent(jsonParamterData, Encoding.UTF8, "application/json");
        client.DefaultRequestHeaders.Add("TenantId", tenantId.ToString());
        client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
        message.Content = content;

        var response = await client.PostAsync(serviceUrl, content);
        var result = await response.Content.ReadAsStringAsync();

        client.Dispose();
    }
  }

我需要从其他方法获取响应结果。

public string GetValue(){

   
}

但是Test() 方法是无效的,那么如何从另一个方法访问Test() 结果值呢?是否可以在 async 方法中返回值。

更新:

[WebMethod(EnableSession = true)]
    public string GetValue(){
       
    }

GetValue() 是一种网络方法

【问题讨论】:

  • 您的 Test 方法应该返回 Task<string> 而不是 void。 async void 只能用于异步事件处理程序。
  • @DavidL 那我怎样才能访问那个方法,你能给我一些完整的代码吗
  • using 块处理IDisposables,包括clientresponse
  • 正如 DavidL 已经说过的,avoid async void。我重复它只是为了发布解释原因的链接。
  • @TheodorZoulias 那么我如何在 Web 方法中使用这些方法。或者有任何可能改变我的Test() 方法

标签: c# asynchronous async-await


【解决方案1】:

你应该这样做,伙计:

public async Task<string> Test(string token, int tenantId, string fromDate,string searchText)
{

    string serviceUrl = "http://localhost/Testapi/api/details/requestDetails/Details";

    string jsonParamterData = new JavaScriptSerializer().Serialize(new
    {
        FromDate = fromDate,
        SearchText = searchText,
    });

    HttpClient client = new HttpClient();

    HttpMethod method = new HttpMethod("POST");
    HttpRequestMessage message = new HttpRequestMessage(method, serviceUrl);

    StringContent content = new StringContent(jsonParamterData, Encoding.UTF8, "application/json");
    client.DefaultRequestHeaders.Add("TenantId", tenantId.ToString());
    client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
    message.Content = content;

    var response = await client.PostAsync(serviceUrl, content);
    var result = await response.Content.ReadAsStringAsync();

    client.Dispose();
    return result;
}

我强烈建议您避免使用 asmx 来执行异步函数,因为它已被弃用和停止使用。为了更清楚,我应该说 async/await 模式在较低版本的网络框架中有一些开销。您至少可以使用基于 dotnet-core 或 .NetFramework 最新版本(如 4.6+)的 Wcf 服务。另一种选择是使用带有基于 Aspnet 或 AspnetCore 的异步/等待承诺的 Rest API。但是,如果您选择继续当前的解决方案,您可以在此处查看以检查 asmx WebMethods 的异步执行: https://docs.microsoft.com/en-us/previous-versions/dotnet/articles/aa480516(v=msdn.10)?redirectedfrom=MSDN

如果你想同时使用 AsyncCallBack 和 async/await 模式,你可以这样做:

public IAsyncResult BeginGetvalue(AsyncCallback cb, Object state)
{
    Action action = async () => {
       string result = await GetValue();
    };

    return action.BeginInvoke(cb, state);
}

我要再次注意:请不要自己这样做。不推荐使用 ASMX 解决方案 :( 使用这些技术来处理您的解决方案:

  • 基于 netcore + kestrel 的异步 Restful api
  • 基于 aspnet-mvc + self-hosted-owin 的异步 Restful api
  • 基于http2+和.net5的Grpc解决方案
  • 网络框架上的 netcore 中的 Wcf 服务。 以上所有技术都支持异步方法。

【讨论】:

  • 假设GetValue() 是一种网络方法。我可以在 web 方法中使用这个吗
  • 您为 WebMethod 使用什么框架/技术? asmx? wcf?网页服务?你的 .net fw 版本是什么?
  • 先生,我正在使用 asmx
  • 亲爱的,我根据您的要求更改了答案
猜你喜欢
  • 2021-04-18
  • 2020-10-17
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多