如何在不等待 httpclient 的情况下 post?

How to post without awaiting with httpclient?

我正在使用 HttpClient post 将数据发送到 Webapi 应用程序。

此代码有效(网络 api 收到 post 调用),但代码正在等待响应。

public static async void Notify(List<string> txs,string url) 
{
    using (HttpClient client = new HttpClient() )
    {
        string resourceAddress = url; 
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        await client.PostAsJsonAsync(resourceAddress, txs);
    }
}

这个不等待来自网络的响应 api 但网络 api 没有收到任何 post 调用:

public static void Notify(List<string> txs,string url) 
{
    using (HttpClient client = new HttpClient() )
    {
        string resourceAddress = url; 
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.PostAsJsonAsync(resourceAddress, txs);
    }
}

我需要调用网络 api 并继续执行代码而无需等待。 我如何使用 HttpClient 做到这一点? 我想完成执行的方法(不包括到里面的其他工作)

I need to call the web api and continue execution of code without waiting. How do I do that with HttpClient ?

当你调用 Notify 时,它应该返回一个 System.Threading.Task,这个任务是管理你的 Notify 方法执行的包装器,反过来PostAsJsonAsync 方法。

public static async Task Notify(List<string> txs,string url) 
{
    using (HttpClient client = new HttpClient() )
    {
        string resourceAddress = url; 
        client.DefaultRequestHeaders.Accept.Add(
           new MediaTypeWithQualityHeaderValue("application/json"));
        return client.PostAsJsonAsync(resourceAddress, txs);
    }
}

您可能正在使用等待调用 Notify。这将在调用位置暂停调用 Notify 的方法(并且对此的调用方法将继续)。如果你不 await 你可以执行其他代码,然后在完成之后你可以 await 来自 Notify 的任务并等待 Post 结束。您将需要等待 post 在某个时间点完成,除非额外的工作比 post 任务本身运行的时间更长。例如

  var task = Notify(someList, someUrl);

  // do a long running task / extra work here, 
  // we have not awaited Notify therefore this will execute whilst the post 
  // is running

  await task;
  // at this point the we have waited for the Notify method to complete, 
  // this will block for the time the post has left to complete (if any at all)

await 告诉您的方法此时暂停执行并等待任务完成。但是如果有一个调用方法,那么调用方法在等待时继续。如果调用方法也 awaits 那么这会一直等到任务完成,调用堆栈中的下一个方法继续,依此类推,直到我们离开代码堆栈并以某种方式结束等待代码完成的非阻塞层(例如 Async ASP.NET MVC,或 Async Winforms UI)。或者我们有一个显式阻塞 Task.Wait 调用。

如果有人还在寻找答案,

public void NotifyAsyncWrapper(IEnumerable<string> txs, string url)
{
    Notify(txs, url).ContinueWith(ContinuationAction, TaskContinuationOptions.OnlyOnFaulted);
}

public async Task Notify(IEnumerable<string> txs, string url)
{
    //async await code
}

private void ContinuationAction(Task task)
{
    if (task.Exception != null)
    {
        logger.LogError(ex, ex.Message);
    }
}