0

让我们从一些代码开始:

class InternetConnector
{
    private struct ConnectionData
    {
        public Action<Socket> SuccessHandler { get; set; }
        public ClientStateObject clientObj { get; set; }
        public Action<Exception> ErrorHandler { get; set; }
        public Socket Socket { get; set; }
    }
    public static ManualResetEvent processingDone = new ManualResetEvent( false );
    public static ConcurrentQueue<string> messages = new ConcurrentQueue<string>();

    public bool ReceiveMessage(Action<Socket> successHandler, Action<Exception> errorHandler)
    {
        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();
                string[] msgs = response.Split('&');
                for (int i = 0; i < msgs.Count(); i++)
                {
                    string sts = msgs[i];
                    messages.Enqueue(sts + "&" );
                }
                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 InternetConnector client = new InternetConnector();
    private bool isRunning = false;

    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;
            isRunning = true;
            client.ReceiveMessage(AsyncSuccessHandler, AsyncErrorHandler);
        }
        else
        {
            GUIChangeOnConnection();
            InternetConnector.processingDone.Set();
        }
    }

    private void GUIChangeOnConnection()
    {
            for( int i = 0; i < InternetConnector.messages.Count; i++ )
            {
                string message;
                InternetConnector.messages.TryDequeue( out message );
// process the message
            }
    }
 }

现在的问题。

一切正常。正在从套接字读取。但是processingDone.WaitOne();,应该无限期地阻止回调的调用,直到调用processingDone.Set();返回太早。

GUIChangeOnConnection();我通过在- 函数右括号行的末尾设置断点来验证它。它到达断点并查看InternetConnector.messages我看到队列不是空的,这意味着 for 循环没有完成。第二次命中此断点时,队列中的消息数量猛增。

我究竟做错了什么?或者我的设计不正确?

谢谢你。

4

0 回答 0