当我尝试连接套接字时,我需要一种分离GUI线程的方法
当我的APP运行时,当lan电缆连接到PC端口时,我的C#代码正常连接而没有挂起GUI。没问题。
但是当没有连接到我的APP尝试连接的PC的Lan端口时,我期望的理想行为是APP等待Socket连接并且GUI不会冻结。
我尝试使用TaskFactory.StartNew Method (Action)
之类的线程
但是我看到它成功解决了GUI挂起但没有连接到局域网sometimes
下面的代码是我最近尝试解决这个问题,但发现它没有用。
try
{
Thread.Sleep(100);
TcpListener serverSocket = new TcpListener(IPAddress.Any,ports);
clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
counter += 1;
dispatcher.Invoke(new Action(() =>
{
clientSocket = serverSocket.AcceptTcpClient();
}));
MessageBox.Show(ports + " " + "Connected!");
}
catch (Exception w)
{
MessageBox.Show(ports + " " + "Connection error!");
}
需要帮助:当没有LAN端口连接到PC时,当APP尝试连接到该端口时,它必须正常等待而不是GUI挂起。
答案 0 :(得分:1)
试试这个:
var ports = 1234;
try
{
Thread.Sleep(100);
var serverSocket = new TcpListener(IPAddress.Any, ports);
var clientSocket = default(TcpClient);
int counter = 0;
serverSocket.Start();
counter += 1;
var source = new CancellationTokenSource();
Task.Factory.StartNew(() =>
{
while(true)
{
clientSocket = serverSocket.AcceptTcpClient();
MessageBox.Show(ports + " " + "Connected!");
}
}, source.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
catch (Exception w)
{
MessageBox.Show(ports + " " + "Connection error!");
}
答案 1 :(得分:1)
您应该使用Async
或Begin
方法(具体取决于您的环境是否支持async / await)。
由于您仅拥有VS2010,您应该使用the Begin
approach:
private void InitializeListiner()
{
var listener = new TcpListener(IPAddress.Any, ports);
listener.Start();
listener.BeginAcceptTcpClient(OnClientConnected, listener);
}
private void OnClientConnected(IAsyncResult asyncResult)
{
var listener = (TcpListener)asyncResult.AsyncState;
var client = listener.EndAcceptTcpClient(asyncResult);
listener.BeginAcceptTcpClient(OnClientConnected, listener);
// ToDo: send and receive data from/to client...
}