0

全部,

有以下问题。首先,这是我的代码:

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]

4

1 回答 1

1

如果我正确理解了这个问题,那么您指的是以下代码点的问题:

if (connectionData.SuccessHandler != null)
{
    connectionData.SuccessHandler(client);
    client.BeginReceive(connectionData.clientObj.buffer, 0, ClientStateObject.bufSize, 0, new AsyncCallback(ReceiveCallback), connectionData);
}

如果您的意图是仅在完成处理以前的数据时才访问服务器,那么SuccessHandler必须是阻塞的(从您的问题陈述中也很明显)。

现在看看你的以下几行SuccessHandler

if (InvokeRequired)
{
    BeginInvoke(new Action( () => AsyncSuccessHandler( socket ) ));
    return;
}

上面的代码推迟了你的执行,SuccessHandler以便 UI 保持响应。或者换句话说,你SuccessHandler没有阻塞。

由于您正在从 更新 GUI SuccessHandler,因此从 UI 线程运行它也很重要(它现在正在正确执行)。

因此,为了进行阻塞,您可以使用机制SuccessHandler使以下代码本身在 UI 线程上运行InvokeRequired

if (connectionData.SuccessHandler != null)
{
    connectionData.SuccessHandler(client);
    client.BeginReceive(connectionData.clientObj.buffer, 0, ClientStateObject.bufSize, 0, new AsyncCallback(ReceiveCallback), connectionData);
}

由于client.BeginReceive是异步的,它不会阻塞 UI 线程,而且您无论如何都想SuccessHandler在 UI 线程上运行..

如果您无权访问 中的表单ReceiveCallback,则可以使用等待句柄来阻止对client.BeginReceive直到SuccessHandler完成的调用。

private static AutoResetEvent _processingDone = new AutoResetEvent( false );
//Introduce an internal property ProcessingDone to access _processingDone 
//This should be in a class which you can access both from 'Form1' and the class containing ReceiveCallBack

//In ReceiveCallBack
if (connectionData.SuccessHandler != null)
{
    connectionData.SuccessHandler(client);
    ProcessingDone.WaitOne();
    client.BeginReceive(connectionData.clientObj.buffer, 0, ClientStateObject.bufSize, 0, new AsyncCallback(ReceiveCallback), connectionData);
}

ProcessingDone.Set() 必须SuccessHandler在您可以确定SuccessHandler已完成并client.BeginReceive需要调用的点从内部完成。这是你的逻辑内部的。从您共享的代码中,很难确定需要放置 ProcessingDone.Set() 的位置。

于 2012-08-17T06:57:52.537 回答