如何在 C# 中调用异步 Web 服务?

how to call async web service in c#?

下面是我目前调用web服务投射的方式,

  public JsonResult CruiseBE_Data1(string cruise)
    {
        CruiseService GetPorts = new CruiseService();
        projectCruise.CruiseServiceASD.ServiceAuthHeader serviceAuthHeaderValue_Cruise = new projectCruise.CruiseServiceASD.ServiceAuthHeader();
        serviceAuthHeaderValue_Cruise.username = "xxxxxxxxxx";
        serviceAuthHeaderValue_Cruise.password = "xxxxxxxxxx";
        GetPorts.ServiceAuthHeaderValue = serviceAuthHeaderValue_Cruise;

        string CruisePorts = "";

        CruisePorts = GetPorts.GetPorts();


        return Json(CruisePorts);
    }

我想做的是将上面的请求更改为异步方式,任何人都可以指导我如何做到这一点。

最简单的方法是将您的 GetPorts.GetPorts() 调用包装在 Task.Run():

CruisePorts = await Task.Run(() => GetPorts.GetPorts());

但请注意,您的方法必须定义为

public async Task<JsonResult> CruiseBE_Data1(string cruise)