gpt4 book ai didi

c# - 尝试在C#中异步读取非结束字节流

转载 作者:太空宇宙 更新时间:2023-11-03 16:51:10 26 4
gpt4 key购买 nike

我正在连接到一个发送财务信息更新的服务器。我在下面发布的代码将正常工作几分钟,然后通常会在它尝试执行 EndRead 时崩溃(我已经注意到),因为当时有 0 个字节要读取。显然,在金融界,有些东西可以在几分钟或更长时间内保持相同的价格,这似乎是我问题的根源。我也怀疑有比我在下面展示的更好的方法来做到这一点。如果您有更有效或更优雅的方法来达到相同的结果,我会洗耳恭听。基本上我现在拥有的代码是从这里和其他地方的随机代码片段组装而成的。我似乎找不到可以按照我需要的方式将所有部分组合在一起的示例。

提前致谢

鲍勃

编辑:我应该澄清一下,我基本上明白出了什么问题,我只是找不到流被关闭的原因。我认为最好的答案是做同样事情的不同实现。我尝试让 WebClient 执行此操作,但没有成功。

public IAsyncResult BeginStreamingData()
{
postUrl = "https://" + "myfinancialbytestreamsource.com/";
byte[] buffer = Encoding.ASCII.GetBytes(postdata);
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(postUrl);
httpWebRequest.AutomaticDecompression = DecompressionMethods.GZip;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.ContentLength = buffer.Length;
httpWebRequest.Timeout = 6000000;
httpWebRequest.ReadWriteTimeout = 6000000;
Stream PostData = httpWebRequest.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();

IAsyncResult result =
(IAsyncResult)httpWebRequest.BeginGetResponse(new AsyncCallback(ResponseCallback), new AsyncState
{
request = httpWebRequest
});

return new CompletedAsyncResult<string>("Completed stream.");
}

internal void ResponseCallback(IAsyncResult asynchronousResult)
{
AsyncState state = asynchronousResult.AsyncState as AsyncState;
HttpWebRequest httpWebRequest = state.request;
state.response = (HttpWebResponse)httpWebRequest.EndGetResponse(asynchronousResult);

Stream responseStream = state.response.GetResponseStream();
byte[] buffer = new byte[1024 * 10];

var completedEvent = new ManualResetEvent(false);

responseStream.BeginRead(buffer, 0, buffer.Length,
AsyncRead,
new AsyncState
{
b = buffer,
s = responseStream,
e = completedEvent
});

completedEvent.WaitOne();
}

private void AsyncRead(IAsyncResult ar)
{
AsyncState state = ar.AsyncState as AsyncState;
int read = 0;

//BLOWS UP HERE (IOException) WHEN IT ENDS A READ THAT HAD 0 BYTES IN IT.

read = state.s.EndRead(ar);

if (read == 0)
{
// signal completion
state.e.Set();
return;
}
else
{
//this is where I'm parsing the bytes into .net objects.
ParseBytes(state.b, read);

}
// read again
state.s.BeginRead(state.b, 0, state.b.Length, AsyncRead, state);
}

//Here is the class that stores the state.
private class AsyncState
{
public Stream s;
public ManualResetEvent e;
public byte[] b;
public HttpWebRequest request;
public HttpWebResponse response;
}

最佳答案

根据文档,只有在流关闭时才会抛出 IOException。所以看起来socket连接已经断开,socket关闭。

IOException 
The stream is closed or an internal error has occurred.

我建议您跟踪错误并重新打开连接。

http://msdn.microsoft.com/en-us/library/system.io.stream.endread.aspx

关于c# - 尝试在C#中异步读取非结束字节流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3928651/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com