尝试在WinForms中实现异步客户/服务器应用程序。客户端代码如下:
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 = "";
}
}
}当我button1发送文本时,UI是冻结的。在欺骗模式下,我发现AsyncCallback(connectCallBack)在线上
clientSocket.BeginConnect(IPAddress.Loopback, 1234, new AsyncCallback(connectCallBack), clientSocket); 不触发,因此connectCallBack没有被执行。程序在网上相当停顿。
sendDone.WaitOne();知道为什么吗?有人能帮忙吗?
发布于 2016-11-18 11:18:42
您正在等待sendDone.WaitOne();,在回电话时使用
connectDone.Set();您应该将sendDone.WaitOne();替换为connectDone.WaitOne();
发布于 2016-11-18 11:21:07
为什么UI会冻结:因为您试图在主线程上连接,所以UI变得没有响应。这是因为UI运行在主线程上。要解决这个问题,请尝试在与主要威胁不同的线程上连接或接收。
为什么回调不称为:您应该用connectDone.WaitOne();替换sendDone.WaitOne();,因为您正在设置connectDone.Set(),并且正在等待sendDone.WaitOne();
https://stackoverflow.com/questions/40675638
复制相似问题