异步socket + waitone()

时间:2012-08-23 07:19:31

标签: c# sockets asynchronous

让我们从一些代码开始:

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循环没有完成。 第二次这个断点被击中时,队列中的消息数量急剧增加。

我做错了什么?或者我的设计可能不正确?

谢谢。

0 个答案:

没有答案