System.ObjectDisposedException:无法访问已处置的对象。对象名称:“ System.Net.Sockets.NetworkStream”。使用HttpClient

时间:2019-10-02 09:43:18

标签: .net-core dotnet-httpclient

我需要同时发送几个Post请求。为此,我将使用以下代码:

        try
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", $"key={customer.FCMServerKey}");

                var obj = new
                {
                    to = customer.FcmRegistrationId,
                    notification = new
                    {
                        title = push.PushTitle,
                        body = push.PushBody,
                    }
                };

                string json = JsonConvert.SerializeObject(obj);
                var data = new StringContent(json, Encoding.UTF8, "application/json");

                responseTasks.Add( client.PostAsync("https://fcm.googleapis.com/fcm/send", data));
                pushes.Add(push);
            }
        }
        catch (HttpRequestException ex)
        {

            Console.WriteLine("\nException with pushing!");
            Console.WriteLine("Message :{0} ", ex.Message);
        }

    }

    var responses = await Task.WhenAll(responseTasks);

    var count = 0;
    foreach (var response in responses)
    {
        var responseBody = await response.Content.ReadAsStringAsync();

        pushes[count].FCMResponse = responseBody;
        pushes[count].Sent = response.IsSuccessStatusCode;

        Console.WriteLine("FCM response:");
        Console.WriteLine(pushes[count].FCMResponse);

        count++;
    }

    await _pushRepository.SaveAsync(pushes);
}

如您所见,我将任务对象放入responseTasks中。然后,我将在此行的帮助下发送所有请求:

var responses = await Task.WhenAll(responseTasks);

我因此有这个例外:

  

未处理的异常:System.Threading.Tasks.TaskCanceledException:操作已取消。 ---> System.ObjectDisposedException:无法访问已处置的对象。   对象名称:“ System.Net.Sockets.NetworkStream”。      在System.Net.Sockets.NetworkStream.WriteAsync(Byte []缓冲区,Int32偏移量,Int32大小,CancellationToken cancelledToken)      在System.IO.Stream.WriteAsync(Byte []缓冲区,Int32偏移量,Int32计数)      在System.Net.Security.SslState.StartSendBlob(Byte []入站,Int32计数,AsyncProtocolRequest asyncRequest)      在System.Net.Security.SslState.ForceAuthentication处(布尔receiveFirst,Byte []缓冲区,AsyncProtocolRequest asyncRequest)      在System.Net.Security.SslState.ProcessAuthentication(LazyAsyncResult lazyResult)      在System.Net.Security.SslStream.BeginAuthenticateAsClient(SslClientAuthenticationOptions sslClientAuthenticationOptions,CancellationToken cancelToken,AsyncCallback asyncCallback,对象asyncState)      在System.Net.Security.SslStream。<> c.b__47_0(SslClientAuthenticationOptions arg1,CancellationToken arg2,AsyncCallback回调,对象状态)      在System.Threading.Tasks.TaskFactory 1.FromAsyncImpl[TArg1,TArg2](Func 5 beginMethod,Func 2 endFunction, Action 1 endAction,TArg1 arg1,TArg2 arg2,Object state,TaskCreationOptions creationOptions处)      位于System.Threading.Tasks.TaskFactory.FromAsync [TArg1,TArg2](Func 5 beginMethod, Action 1 endMethod,TArg1 arg1,TArg2 arg2,对象状态,TaskCreationOptions creationOptions)      在System.Threading.Tasks.TaskFactory.FromAsync [TArg1,TArg2](Func 5 beginMethod, Action 1 endMethod,TArg1 arg1,TArg2 arg2,对象状态)处      在System.Net.Security.SslStream.AuthenticateAsClientAsync(SslClientAuthenticationOptions sslClientAuthenticationOptions,CancellationToken cancellingToken)      在System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream,SslClientAuthenticationOptions sslOptions,CancellationToken cancelledToken)      ---内部异常堆栈跟踪的结尾---      在System.Net.Http.ConnectHelper.EstablishSslConnectionAsyncCore(Stream stream,SslClientAuthenticationOptions sslOptions,CancellationToken cancellingToken)

怎么了?

1 个答案:

答案 0 :(得分:3)

请检查使用方式: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

在您的代码中,client将在using块结束时立即被处理掉,但是responseTasks列表上仍有待处理的任务将尝试访问它。您需要在client中使用block获得结果。