【发布时间】:2019-10-31 05:28:25
【问题描述】:
所以我试图制作一个可以执行从客户端发送的函数的应用程序,它工作正常,但 UI 在侦听来自客户端的消息时冻结,我必须更改什么才能使此代码异步运行?已经尝试将 public void ExecuteServer(string pwd) 更改为 public async task ExecuteServer(string pwd) 但它只是告诉我我缺少等待
//Where im calling it
public Form2()
{
InitializeComponent();
(ExecuteServer("test"));
}
//The Network Socket im trying to run Async
public static void ExecuteServer(string pwd)
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true)
{
//Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
if(data == "<EOF> " + "kill")
{
Application.Exit();
}
else if (data == "<EOF>" + "getpw")
{
sendtoclient(clientSocket, pwd);
}
else
{
sendtoclient(clientSocket, "Error 404 message not found!");
}
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e)
{
//Console.WriteLine(e.ToString());
}
}
【问题讨论】:
-
你试过Task.Run(() => ExecuteServer("test"));没有任何其他异步语法?
-
虽然其他答案在使用 await Task.Run(() => {...}); 时是正确的;这背后的原因是因为UI是在单线程上运行的,如果你想运行一些像更新进度条这样的代码,它会锁定UI的线程并专注于进度条,或者其他与UI无关的后台代码就像您的网络代码一样。使用 await Task.Run(() => {...});将另一个线程专用于一些后台工作。希望这会有所帮助。
-
由于您在服务器循环期间没有做任何与 UI 相关的操作,我建议您使用老式线程而不是
Task.Run。你可以找到很多关于如何做到这一点的教程和资源。其中许多甚至使用套接字。
标签: c# asynchronous