使用client.GetAsync(url)的脚本任务不等待响应

时间:2018-11-06 20:37:13

标签: c#

我正在siss中运行脚本任务来调用此API,但它没有在完成之前等待响应。还有什么需要做的吗?

public void Main()
{

    GetRequest(Dts.Variables["User::URL"].Value.ToString());
    Dts.TaskResult = (int)ScriptResults.Success;
}

private static void GetRequest(string url)
{
   try
   {
      HttpClient client = new HttpClient();
      HttpResponseMessage response = client.GetAsync(url).Result;
      response.EnsureSuccessStatusCode();
   }
   catch (Exception e)
   {
      System.Console.WriteLine("Caught Exception: " + e.Message);
   }
}

尝试过这个,但仍然没有等待:

    public async System.Threading.Tasks.Task MainAsync()
    {

        await GetRequestAsync(Dts.Variables["User::URL"].Value.ToString());
        Dts.TaskResult = (int)ScriptResults.Success;
    }

    private static async Task GetRequestAsync(string url)
    {
        try
        {
            HttpClient client = new HttpClient();
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();
        }
        catch (Exception e)
        {
            System.Console.WriteLine("Caught Exception: " + e.Message);
        }
    }

1 个答案:

答案 0 :(得分:-1)

尝试此操作,您将需要将该方法标记为异步Task,然后等待“ client.GetAsync(url);”。呼叫

private static async Task GetRequestAsync(string url)
{
    try
    {
        HttpClient client = new HttpClient();
        HttpResponseMessage response = await client.GetAsync(url);
        response.EnsureSuccessStatusCode();
    }
    catch (Exception e)
    {
        System.Console.WriteLine("Caught Exception: " + e.Message);
    }
}

最重要的是,您可以在方法被调用时专门等待它