全部,
有以下问题。首先,这是我的代码:
class InternetConnector
{
private static ManualResetEvent receiveDone = new ManualResetEvent( false );
public static ManualResetEvent processingDone = new ManualResetEvent( false );
public static ConcurrentQueue<string> messages = new ConcurrentQueue<string>();
public static bool Connected;
public bool ReceiveMessage(Action<Socket> successHandler, Action<Exception> errorHandler)
{
bool receive = false;
ClientStateObject obj = new ClientStateObject();
obj.server = client;
var connectionData = new ConnectionData
{
ErrorHandler = errorHandler,
SuccessHandler = successHandler,
Socket = client,
clientObj = obj
};
if (Connected)
{
client.BeginReceive(connectionData.clientObj.buffer, 0, ClientStateObject.bufSize, 0, new AsyncCallback(ReceiveCallback), connectionData);
receive = true;
receiveDone.WaitOne();
}
return receive;
}
private static void ReceiveCallback(IAsyncResult ar)
{
ConnectionData connectionData = new ConnectionData();
bool complete = false;
try
{
connectionData = (ConnectionData)ar.AsyncState;
Socket client = connectionData.Socket;
int num = client.EndReceive(ar);
{
connectionData.clientObj.stringBuffer.Append(Encoding.ASCII.GetString(connectionData.clientObj.buffer, 0, num));
string response = connectionData.clientObj.stringBuffer.ToString();
if (response.EndsWith("&"))
complete = true;
string[] msgs = response.Split('&');
int j = 0;
if (!complete)
j++;
for (int i = 0; i < msgs.Count() - j; i++)
{
string sts = msgs[i];
if (i == 0 && receivingMessage != String.Empty)
{
sts = receivingMessage + sts;
messages.Enqueue(sts + "&" );
receivingMessage = String.Empty;
}
else
messages.Enqueue(sts + "&");
}
if (!complete)
receivingMessage += msgs[msgs.Count() - 1];
else
receivingMessage = String.Empty;
receiveDone.Set();
if (connectionData.SuccessHandler != null)
{
connectionData.SuccessHandler(client);
processingDone.WaitOne();
client.BeginReceive(connectionData.clientObj.buffer, 0, ClientStateObject.bufSize, 0, new AsyncCallback(ReceiveCallback), connectionData);
}
}
}
catch (Exception e)
{
if (connectionData.ErrorHandler != null)
connectionData.ErrorHandler(e);
}
}
}
这是成功处理程序:
public partial class Form1 : Form
{
private void AsyncSuccessHandler(Socket socket)
{
if (InvokeRequired)
{
BeginInvoke(new Action( () => AsyncSuccessHandler( socket ) ));
return;
}
if (InternetConnector.messages.Count() == 0)
{
status.Text = "Signals Receiver: Connected";
status.ForeColor = Color.Green;
startStop.Text = "Stop";
isRunning = true;
create.Enabled = true;
SetGUIColorsAndValues();
client.SendMessageToConnector("First Signal Pass4&");
client.ReceiveMessage(AsyncSuccessHandler, AsyncErrorHandler);
}
else
{
SetGUIColorsAndValues();
GUIChangeOnConnection();
InternetConnector.processingDone.Set();
}
}
private void GUIChangeOnConnection()
{
for( int i = 0; i < InternetConnector.messages.Count; i++ )
{
string message;
InternetConnector.messages.TryDequeu( out message );
// process message
}
}
}
问题:我需要不断地从服务器读取数据并在 GUI 中显示它们。我还需要 GUI 来响应按钮点击。当 n-1 次读取迭代已完成处理并且我的代码中的并发队列对象为空时,我还需要启动 n 次读取迭代。
但是通过调试器中的代码,我可以看到读取回调中的 BeginReceive() 调用不会等到成功处理程序结束并且队列不为空。
我错过了什么?有没有更好的方法来实现这一目标?
我也知道 SignalR 库,但在这个桥上我不想使用任何 3rd 方库。
对此问题的任何帮助表示赞赏。
谢谢你。
[编辑]
我是否正确理解 Amit 的回复:
class InternetConnector
{
private static ManualResetEvent processingDone = new ManualResetEvent( false );
private static void ReceiveCallback(IAsyncResult ar)
{
ConnectionData connectionData = new ConnectionData();
bool complete = false;
try
{
connectionData = (ConnectionData)ar.AsyncState;
Socket client = connectionData.Socket;
int num = client.EndReceive(ar);
{
connectionData.clientObj.stringBuffer.Append(Encoding.ASCII.GetString(connectionData.clientObj.buffer, 0, num));
string response = connectionData.clientObj.stringBuffer.ToString();
if (response.EndsWith("&"))
complete = true;
string[] msgs = response.Split('&');
int j = 0;
if (!complete)
j++;
for (int i = 0; i < msgs.Count() - j; i++)
{
string sts = msgs[i];
if (i == 0 && receivingMessage != String.Empty)
{
sts = receivingMessage + sts;
messages.Enqueue(sts + "&" );
receivingMessage = String.Empty;
}
else
messages.Enqueue(sts + "&");
}
if (!complete)
receivingMessage += msgs[msgs.Count() - 1];
else
receivingMessage = String.Empty;
receiveDone.Set();
if (connectionData.SuccessHandler != null)
{
processingDone.WaitOne();
connectionData.SuccessHandler(client);
processingDone.Set();
client.BeginReceive(connectionData.clientObj.buffer, 0, ClientStateObject.bufSize, 0, new AsyncCallback(ReceiveCallback), connectionData);
}
}
}
catch (Exception e)
{
if (connectionData.ErrorHandler != null)
connectionData.ErrorHandler(e);
}
}
}
?
[/EDIT] [EDIT 2] 请查看更新的代码。当我在 GUIChangeOnConnection() 的最后设置断点时 - 与“}”行 - 我看到队列确实有一些项目。同时,我将尝试更改 ManualResetEvent。[/编辑 2]