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
最满意答案
不可能完全动态地改变流处理管道的结构。 我们确实预见了某些动态处理阶段(例如“可能来来往往的工人扇动”),但一般来说,溪流和溪流处理管道在实施前应该有一个确定的布局。 这也是有意义的,因为一般在阿卡流和反应流中使用的背压机制 - 它必须在内部谨慎管理,并且允许任意交互仅仅是这个流模型所设计的。
如果你想要任意的互动,演员应该更适合你。 如果你想拥有一个处理单元,可以采用外部信号来引导处理流水线,那么它将成为这个物化管道中的一个特殊单元,用于接收这些信号,而不仅仅是任何单元。
自从我发布这篇文章后,我们添加了一些动态功能,这些功能可能对登陆此网站的人感兴趣,最显着的是MergeHub和BroadcastHub
请注意,正如编写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
.
相关问答
更多-
我如何发布或订阅物化Akka Stream流程图?(How can I publish or subscribe to a materialized Akka Stream flow graph?)[2023-03-13]
不可能完全动态地改变流处理管道的结构。 我们确实预见了某些动态处理阶段(例如“可能来来往往的工人扇动”),但一般来说,溪流和溪流处理管道在实施前应该有一个确定的布局。 这也是有意义的,因为一般在阿卡流和反应流中使用的背压机制 - 它必须在内部谨慎管理,并且允许任意交互仅仅是这个流模型所设计的。 如果你想要任意的互动,演员应该更适合你。 如果你想拥有一个处理单元,可以采用外部信号来引导处理流水线,那么它将成为这个物化管道中的一个特殊单元,用于接收这些信号,而不仅仅是任何单元。 自从我发布这篇文章后,我们添加了 ... -
如何在前一阶段传递Akka Stream Flow中的参数?(How to pass parameters in Akka Stream Flow from a previous stage?)[2023-07-06]
您对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连接。 ...
-
akka流自定义图阶段(akka stream custom graph stage)[2022-04-11]
一个问题是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 = ...
-
与akka群集的akka小河(akka-streams with akka-cluster)[2023-07-15]
你可能想让你的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)( ...