我用BeginRead
,但繼續阻止使用WaitHandle
螺紋:
byte[] readBuffer = new byte[32];
var asyncReader = stream.BeginRead(readBuffer, 0, readBuffer.Length,
null, null);
WaitHandle handle = asyncReader.AsyncWaitHandle;
// Give the reader 2seconds to respond with a value
bool completed = handle.WaitOne(2000, false);
if (completed)
{
int bytesRead = stream.EndRead(asyncReader);
StringBuilder message = new StringBuilder();
message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));
}
基本上它允許異步的超時使用WaitHandle
讀取併爲您提供了一個布爾值(completed
)如果讀取在設定的時間內完成(在這種情況下爲2000
)。
這裏的複製,並從我的Windows Mobile項目之一粘貼我的全碼流閱讀代碼:
private static bool GetResponse(NetworkStream stream, out string response)
{
byte[] readBuffer = new byte[32];
var asyncReader = stream.BeginRead(readBuffer, 0, readBuffer.Length, null, null);
WaitHandle handle = asyncReader.AsyncWaitHandle;
// Give the reader 2seconds to respond with a value
bool completed = handle.WaitOne(2000, false);
if (completed)
{
int bytesRead = stream.EndRead(asyncReader);
StringBuilder message = new StringBuilder();
message.Append(Encoding.ASCII.GetString(readBuffer, 0, bytesRead));
if (bytesRead == readBuffer.Length)
{
// There's possibly more than 32 bytes to read, so get the next
// section of the response
string continuedResponse;
if (GetResponse(stream, out continuedResponse))
{
message.Append(continuedResponse);
}
}
response = message.ToString();
return true;
}
else
{
int bytesRead = stream.EndRead(asyncReader);
if (bytesRead == 0)
{
// 0 bytes were returned, so the read has finished
response = string.Empty;
return true;
}
else
{
throw new TimeoutException(
"The device failed to read in an appropriate amount of time.");
}
}
}
您確定遠程端正在正確關閉連接嗎?我從來沒有遇到過`Read`沒有回覆的問題。否則你的方法似乎是正確的方向。 – 2010-12-08 15:02:42
@Matthew好吧,說實話,我無法肯定地說。它是我們正在閱讀的第三方服務。他們已經指定了關機時間,我們假設它發生在前面提到的情況。我只想先檢查並重新檢查我的結局,然後再向他們舉起一面旗幟。 – 2010-12-09 05:55:27