我使用C#并通过webapi我需要向服务器发送请求并处理响应。从服务器返回的数据格式如下:
{"A_Field":a,"B_Field":"B_FieldValue","C_Field":5}
{"TYPE":"Values","Column1":["1234","456789","12345"],"Column2":["abc","defg","high"]}
{"TYPE":"Values","Column1":["45353","23422","6755"],"Column2":["sfs","fhfghg","vzczzc"]}
{"TYPE":"Values","Column1":["4564","5664","12345"],"Column2":["abfsdc","vxvx","cxvbvx"]}
{"TYPE":"Values","Column1":["5664","979","7978"],"Column2":["ryrt","qweq","nbmm"]}
....
{"A_Field":b,"COMPLETE:"YES"}
我需要处理以{" TYPE":"值" ....}开头的部分 从服务器返回的消息量非常大。因此,能够处理收到的每条线路/消息是理想的。最后一行有" COMPLETE:" YES"}表示消息结束。我尝试了以下代码:
try{
using (var handler = new HttpClientHandler())
{
handler.Credentials = new System.Net.NetworkCredential("user", "password");
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("http://<server>:port/api/rest/");
await client.GetAsync(blah_query)
.ContinueWith(taskwithresponse =>
HttpResponseMessage response = taskwithresponse.Result;
}
}
}
catch(Exception e)
{
Console.WriteLine("Error {0}",e.Message);
}
输出结果为:
Error: System.AggregateException: One or more errors occurred. ---> System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.IO.MemoryStream.set_Capacity(Int32 value)
at System.IO.MemoryStream.EnsureCapacity(Int32 value)
at System.IO.MemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Http.HttpContent.LimitMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Http.StreamToStreamCopy.TryStartWriteSync(Int32 bytesRead)
at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task 1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task 1.get_Result() at WebCall.Program.
at System.Threading.Tasks.ContinuationTaskFromResultTask`1.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) atSystem.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at WebCall.Program.<RunAsync>d__3.MoveNext() in
---> (Inner Exception #0) System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
...
at System.Net.Http.HttpContent.LimitMemoryStream.Write(Byte[] buffer, Int32 offset, Int32 count)
at System.Net.Http.StreamToStreamCopy.TryStartWriteSync(Int32 bytesRead)
at System.Net.Http.StreamToStreamCopy.BufferReadCallback(IAsyncResult ar)<---
当响应非常大时,这会失败。我猜测必须在循环中完成处理?但我相信这里发生的事情是等待整个信息的回归。或者这是完全错误的方式。
我不熟悉网络编程。但有人可以帮助建议我如何以最佳方式处理返回的数据?是否可以一次执行一行/消息?代码示例/教程将是一个很好的帮助。我所看到的大部分内容都使用了少量数据。
有谁知道我是如何进步的?