首页 \ 问答 \ HttpClient上的ObjectDisposedException(ObjectDisposedException on HttpClient)

HttpClient上的ObjectDisposedException(ObjectDisposedException on HttpClient)

我有一个Windows通用项目与多个API调用。 一种方法拒绝工作事件我的其他调用完全像这样工作。 我曾尝试using关键字认为它可以解决问题。

功能:

public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
    String userguidJSON = VALIDJSON_BELIEVE_ME;
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));

        using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
        {
            req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
            await httpClient.SendAsync(req).ContinueWith(respTask =>
            {
                Debug.WriteLine(req.Content.ReadAsStringAsync()); //Error is thrown ono this line
            });
            return null;
        }
    }
}

编辑

public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
    String userguidJSON = VALIDJSON_BELIEVE_ME;
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));

        using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
        {
            req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
            await httpClient.SendAsync(req);
            var result = await req.Content.ReadAsStringAsync(); //Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'.
            Debug.WriteLine(result);
            return null;
        }
    }
}

堆栈跟踪

 at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.ReadAsStringAsync()
   at Roadsmart.Service.RoadsmartService.<GetNewUser>d__2e.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Roadsmart.ViewModel.SettingsPageViewModel.<SetNewProfilePicture>d__1e.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__3(Object state)
   at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()

I have a Windows Universal Project with multiple API calls. One method refuses to work eventhought my other calls work perfectly like this. I have tried the using keyword thought it would resolve the issue.

The function:

public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
    String userguidJSON = VALIDJSON_BELIEVE_ME;
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));

        using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
        {
            req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
            await httpClient.SendAsync(req).ContinueWith(respTask =>
            {
                Debug.WriteLine(req.Content.ReadAsStringAsync()); //Error is thrown ono this line
            });
            return null;
        }
    }
}

EDIT

public async Task<User> GetNewUser(string user_guid, OAuthTokens OAuth)
{
    String userguidJSON = VALIDJSON_BELIEVE_ME;
    using (var httpClient = new HttpClient())
    {
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Authorization", Encrypt(OAuth.Accesstoken));

        using (HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, BASE_URL + URL_USERS + "/data"))
        {
            req.Content = new StringContent(userguidJSON, Encoding.UTF8, "application/json");
            await httpClient.SendAsync(req);
            var result = await req.Content.ReadAsStringAsync(); //Cannot access a disposed object. Object name: 'System.Net.Http.StringContent'.
            Debug.WriteLine(result);
            return null;
        }
    }
}

The stacktrace

 at System.Net.Http.HttpContent.CheckDisposed()
   at System.Net.Http.HttpContent.ReadAsStringAsync()
   at Roadsmart.Service.RoadsmartService.<GetNewUser>d__2e.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Roadsmart.ViewModel.SettingsPageViewModel.<SetNewProfilePicture>d__1e.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<ThrowAsync>b__3(Object state)
   at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()

原文:https://stackoverflow.com/questions/29369945
更新时间:2024-02-21 13:02

最满意答案

不可能完全动态地改变流处理管道的结构。 我们确实预见了某些动态处理阶段(例如“可能来来往往的工人扇动”),但一般来说,溪流和溪流处理管道在实施前应该有一个确定的布局。 这也是有意义的,因为一般在阿卡流和反应流中使用的背压机制 - 它必须在内部谨慎管理,并且允许任意交互仅仅是这个模型所设计的。

如果你想要任意的互动,演员应该更适合你。 如果你想拥有一个处理单元,可以采用外部信号来引导处理流水线,那么它将成为这个物化管道中的一个特殊单元,用于接收这些信号,而不仅仅是任何单元。


自从我发布这篇文章后,我们添加了一些动态功能,这些功能可能对登陆此网站的人感兴趣,最显着的是MergeHubBroadcastHub

请注意,正如编写Akka Streams的稳定版本是2.4.16


It is not possible to completely dynamically change structures of stream processing pipelines. We do foresee certain kinds of dynamic processing stages (like an "fanout to workers which may come and go"), but in general streams and stream processing pipelines should have a defined layout before materialisation. This also makes sense because of the back-pressure mechanisms employed in akka-streams and reactive-streams in general – it has to be carefully managed internally, and allowing arbitrary interactions is just not something this streaming model is designed for.

If you want arbitrary interactions, Actors should suit you better. If you want to have a processing element that can take external signals to steer the processing pipeline, it would be a special element inside that materialised pipeline designed to take in these signals, not just any element.


Since I published this post we added some dynamic features, which may be of interest to people who land on this site, most notably the MergeHub and the BroadcastHub

Please note that as ow writing the stable version of Akka Streams is 2.4.16.

相关问答

更多
  • 不可能完全动态地改变流处理管道的结构。 我们确实预见了某些动态处理阶段(例如“可能来来往往的工人扇动”),但一般来说,溪流和溪流处理管道在实施前应该有一个确定的布局。 这也是有意义的,因为一般在阿卡流和反应流中使用的背压机制 - 它必须在内部谨慎管理,并且允许任意交互仅仅是这个流模型所设计的。 如果你想要任意的互动,演员应该更适合你。 如果你想拥有一个处理单元,可以采用外部信号来引导处理流水线,那么它将成为这个物化管道中的一个特殊单元,用于接收这些信号,而不仅仅是任何单元。 自从我发布这篇文章后,我们添加了 ...
  • 您对stageB定义stageB构建一个Flow[StreamResult, StreamResult, _] 。 它不需要将(input: StreamResult)作为参数。 请注意,您不会在stageB定义中的任何位置使用input 。 该元素来自您要map的Flow[StreamResult] 。 这应该足够了: def stageB(externalService: Set[Int]) = … // As you wrote it val graph = Source.single(InitEl ...
  • 事实证明,无法将元素添加到从队列中创建的源中创建的元素。 集合中的可用元素将在流的实现过程中传递,并且在处理这些元素时将完成流。 因为cmbaxter提到创建一个Source,通过ActorPublisher创建一个Source,可以在实现物化后添加元素。 Akka文件: http://doc.akka.io/docs/akka-stream-and-http-experimental/1.0-RC3/java/stream-integrations.html#ActorPublisher 相关问题: 如何 ...
  • 你尝试使用Source.lazily()吗? 以下是它的scala doc所说的内容: 创建直到有下游需求时才实现的源,当源实现物化时,实体化未来以其值完成,如果下游取消或没有任何需求失败,则永不会调用创建工厂,并且物化Future将失败。 另见: https : //doc.akka.io/docs/akka/2.5.6/scala/stream/stages-overview.html#lazily 那是: sourceA.concat(Source.lazily(() => sourceB)) Di ...
  • 您可以使用两种不同的策略,具体取决于您从“cityRequestEndpoint”获取的实体的性质: 基于流 处理这种情况的典型方法是始终假设来自源端点的实体可以包含N个数据,其中N是事先未知的。 这通常是要遵循的模式,因为它是现实世界中最通用的,因此是“最安全的”。 第一步是将来自端点的HttpResponse转换为数据源: val convertResponseToByteStrSource : (Try[HttpResponse], User) => Source[(Option[ByteString ...
  • 不.WebSocket是双向通道,因此Akka-HTTP将其建模为Flow 。 如果在您的特定情况下您只关心通道的一侧,则可以通过使用Flow.fromSinkAndSource(Sink.ignore, mySource)或Flow.fromSinkAndSource(mySink, Source.maybe)由您来形成具有“静音”侧的Flow.fromSinkAndSource(mySink, Source.maybe) ,视情况而定。 根据文件 : 将根据空闲超时设置删除非活动WebSocket连接。 ...
  • 一个问题是incoming阶段,它被建模为一个Sink 。 它应该被建模为一个Flow 。 随后将消息提供给Kafka。 因为传入的文本消息可以是Streamed传输。 您可以按如下方式使用flatMapMerge组合器,以避免在内存中存储整个(可能很大的)消息: val incoming: Flow[Message, String, NotUsed] = Flow[Message].mapAsync(4) { case msg: BinaryMessage => msg.dataS ...
  • 从Akka Streams 2.4.3开始,有一种优雅的方式可以通过KillSwitch阻止来自外部的流。 请考虑以下示例,该示例在10秒后停止流。 object ExampleStopStream extends App { implicit val system = ActorSystem("streams") implicit val materializer = ActorMaterializer() import system.dispatcher val source = ...
  • 你可能想让你的Actor扩展ActorPublisher。 然后,您可以从中创建一个源并将其集成到您的流中。 请参阅此处有关ActorPublisher的文档: http ://doc.akka.io/docs/akka-stream-and-http-experimental/2.0.3/scala/stream-integrations.html You probably want to make your Actor extend ActorPublisher. Then you can create ...
  • 创建涉及异步计算的Flow的最简单方法是使用mapAsync 。 所以......假设你想要创建一个使用异步计算mapper: Int => Future[String]消耗Int并生成String的Flow mapper: Int => Future[String] ,并行度为5。 val mapper: Int => Future[String] = (i: Int) => Future(i.toString) val yourFlow = Flow[Int].mapAsync[String](5)( ...

相关文章

更多

最新问答

更多
  • 获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)
  • 如何通过引用返回对象?(How is returning an object by reference possible?)
  • 矩阵如何存储在内存中?(How are matrices stored in memory?)
  • 每个请求的Java新会话?(Java New Session For Each Request?)
  • css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)
  • 无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)
  • xcode语法颜色编码解释?(xcode syntax color coding explained?)
  • 在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)
  • 从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)
  • 从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))
  • 西安哪有PLC可控制编程的培训
  • 在Entity Framework中选择基类(Select base class in Entity Framework)
  • 在Android中出现错误“数据集和渲染器应该不为null,并且应该具有相同数量的系列”(Error “Dataset and renderer should be not null and should have the same number of series” in Android)
  • 电脑二级VF有什么用
  • Datamapper Ruby如何添加Hook方法(Datamapper Ruby How to add Hook Method)
  • 金华英语角.
  • 手机软件如何制作
  • 用于Android webview中图像保存的上下文菜单(Context Menu for Image Saving in an Android webview)
  • 注意:未定义的偏移量:PHP(Notice: Undefined offset: PHP)
  • 如何读R中的大数据集[复制](How to read large dataset in R [duplicate])
  • Unity 5 Heighmap与地形宽度/地形长度的分辨率关系?(Unity 5 Heighmap Resolution relationship to terrain width / terrain length?)
  • 如何通知PipedOutputStream线程写入最后一个字节的PipedInputStream线程?(How to notify PipedInputStream thread that PipedOutputStream thread has written last byte?)
  • python的访问器方法有哪些
  • DeviceNetworkInformation:哪个是哪个?(DeviceNetworkInformation: Which is which?)
  • 在Ruby中对组合进行排序(Sorting a combination in Ruby)
  • 网站开发的流程?
  • 使用Zend Framework 2中的JOIN sql检索数据(Retrieve data using JOIN sql in Zend Framework 2)
  • 条带格式类型格式模式编号无法正常工作(Stripes format type format pattern number not working properly)
  • 透明度错误IE11(Transparency bug IE11)
  • linux的基本操作命令。。。