UI flow during while
-
Why do I have a UI flow when I do
While
, well, it was understandable if I would have done this cycle in a normal way, so I made the method asynchronous and still hangs, why?private async void button_Click(object sender, RoutedEventArgs e) { while (true) // С этим while'ом работает всё ок { Task processTask = Process(lastclient); } }
async Task Process(TcpClient result)
{
... тут что-то происходит
while (true) // С этим while'ом всё повисает
{
result.Client.Receive(recievebytes);
}
}
UPD 1 :
SocketAsyncEventArgs eventArgObjectForPool = new SocketAsyncEventArgs();
eventArgObjectForPool.UserToken = users.Last<TcpClient>().Client;result.Client.ReceiveFromAsync(eventArgObjectForPool); //Вот тут вылетает, какого то параметра не хватает внутри eventArgObjectForPool
UPD 2 :
TcpListener listener;
TcpClient user;private async void button_Click(object sender, RoutedEventArgs e) //По нажатии на клавишу запускаем наш серв { TcpListener listener = new TcpListener(listenPort); listener.Start(); TcpClient user = await listener.AcceptTcpClientAsync() while (true) { Process(user); //Если клиент подключён, то начинаем с ним работать } } async Task Process(TcpClient result) { //Тут настраиваем слушалку для клиента SocketAsyncEventArgs eventArgObjectForPool = new SocketAsyncEventArgs(); eventArgObjectForPool.UserToken = user.Client; eventArgObjectForPool.RemoteEndPoint = user.Client.RemoteEndPoint; eventArgObjectForPool.Completed += EventArgObjectForPool_Completed; listener.Server.ReceiveFromAsync(eventArgObjectForPool); // Вот это я как понимаю ставлю обработчик на входящие сообщения } private void EventArgObjectForPool_Completed(object sender, SocketAsyncEventArgs e) { Console.WriteLine("ads"); // Если что-то приходит от клиента, то выводим в консоль строку какую-нибудь. }
-
result.Client.Receive(recievebytes);
- it's a sync call. Of course, the flow of UI will be hanging, but it's synchronically reading from the soquet in an endless cycle!Libo Find out. asynchronous version of the method
Receive
:async Task Process(TcpClient result) { while(true) { count += await result.Client.ReceiveAsync(recievebytes); } }
Either you take a reading into a separate flow.