简体   繁体   中英

AsyncCallback not firing

Trying to implement Asynchronous Client/Server app in WinForms. Clientside code is as following:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace AsyncClient
{
    public partial class AsyncClient : Form
    {
        public AsyncClient()
        {
            InitializeComponent();
        }

        //ManualResetEvent for notifying asyncronous threads that an event has occured
        private static ManualResetEvent connectDone = new ManualResetEvent(false);
        private static ManualResetEvent sendDone = new ManualResetEvent(false);
        private static ManualResetEvent receiveDone = new ManualResetEvent(false);

        //Response from the remote device (server)
        private static String response = String.Empty;

        //start client
        private void button1_Click(object sender, EventArgs e)
        {
            TcpClient clientSocket = new TcpClient();
            try
            {
                var message = System.Text.Encoding.UTF8.GetBytes(txtFromClient.Text); //convert message to bytes for sending over the wire
                using (clientSocket)/*(var clientSocket = new TcpClient("127.0.0.1", 1234)) *///make connection with the host
                {
                    clientSocket.BeginConnect(IPAddress.Loopback, 1234, new AsyncCallback(connectCallBack), clientSocket);
                    sendDone.WaitOne();
                    lblConnectionStatus.Text = "Connect is successfully established with the remote device.";
                    //send data to remote device
                    NetworkStream stream = clientSocket.GetStream(); //obtain network stream
                    stream.Write(message, 0, message.Length); //send data to the remote device
                    //sendDone.WaitOne();
                }
            }
           finally
            {
                clientSocket.Close();
            }
        }

        private static void connectCallBack(IAsyncResult ar)
        {
            try
            {
                var clientSocket = (TcpClient)ar.AsyncState; //retrieve socket from state object (IAsyncResult)
                clientSocket.EndConnect(ar); //complete the connection
                connectDone.Set();
            }
            finally
            {

            }
        }

        private void txtFromClient_Click(object sender, EventArgs e)
        {
            txtFromClient.Text = "";
        }
    }
}

When I button1 to send text, UI is freezing. During dubug mode I found that AsyncCallback(connectCallBack) in line

clientSocket.BeginConnect(IPAddress.Loopback, 1234, new AsyncCallback(connectCallBack), clientSocket); 

is not firing and hence connectCallBack is not being executed. Program is rather halt on line

sendDone.WaitOne();

Any ideas why? Can someone please help?

You are waiting for sendDone.WaitOne(); and in your call back you use

connectDone.Set();

You should replace sendDone.WaitOne(); with connectDone.WaitOne();

Why the UI is freezing : because you are trying to connect on the main thread so the UI becomes unresponsive. this is because the UI runs on the main thread. To solve this try to connect or receive on an different thread than the main threat.

Why the callback is not called : you should replace sendDone.WaitOne(); with connectDone.WaitOne(); because you are setting connectDone.Set() and you are waiting for sendDone.WaitOne();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM