C#异步套接字客户端阻止主界面线程(C# Async Socket Client Blocks Main Interface Thread)

编程入门 行业动态 更新时间:2024-10-27 14:34:22
C#异步套接字客户端阻止主界面线程(C# Async Socket Client Blocks Main Interface Thread)

此次的另一个网络问题与异步套接字客户端有关,该客户端至少基于MSDN示例的初始版本。 目前,当用户单击界面上的按钮时,Async Connect尝试连接到联网设备,代码如下所示 -

//Mouse Event handler for main thread private void btn_Read_MouseDown(object sender, MouseEventArgs e) { Stopwatch sw = Stopwatch.StartNew(); if (!networkDev.Connected) networkDev.Connect("192.168.1.176", 1025); if(networkDev.Connected) networkDev.getReading(); sw.Stop();//Time time taken... }

如果终点已打开且存在于网络上,则此代码可正常工作(整个操作不到一秒钟)。 但是,如果联网设备被关闭或不可用,则AsyncSocket Connect功能会保留主表单线程。 目前,如果设备不可用,整个界面会锁定大约20秒(使用秒表)。 我认为我锁定因为主线程正在等待Connect请求的返回,这是否意味着我需要将该连接请求放在另一个线程上?

我已经包含了我正在使用的异步套接字客户端的代码 -

public bool Connect(String ip_address, UInt16 port) { bool success = false; try { IPAddress ip; success = IPAddress.TryParse(ip_address, out ip); if (success) success = Connect(ip, port); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); } return success; } public bool Connect(IPAddress ip_address, UInt16 port) { mSocket.BeginConnect(ip_address, port, new AsyncCallback(ConnectCallback), mSocket); connectDone.WaitOne();//Blocks until the connect operation completes, //(time taken?) timeout? return mSocket.Connected; } private void ConnectCallback(IAsyncResult ar) { //Retreive the socket from thestate object try { Socket mSocket = (Socket)ar.AsyncState; //Set signal for Connect done so that thread will come out of //WaitOne state and continue connectDone.Set(); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); } }

我希望通过使用具有自己的线程的Async客户端,如果主机不存在,那么这将停止冻结接口,但这似乎不是这种情况。 在初始连接失败(需要20秒)之后,立即返回所有后续连接尝试(小于1毫秒)。 还有一些我认为奇怪的事情,如果初始连接尝试成功,任何以后连接到不存在的主机的调用都会立即返回。 有点困惑的是发生了什么,但想知道它是否与我使用的Socket存储在我的AsyncSocket类中的事实有关。 任何帮助非常感谢,如果需要更多的客户端代码,请告诉我。

Another networking question this time related to an Async Socket Client which is based on the MSDN examples at least for this initial version. Currently when the user clicks a button on the interface an Async Connect attempt is made to connect to a networked device, the code is shown below -

//Mouse Event handler for main thread private void btn_Read_MouseDown(object sender, MouseEventArgs e) { Stopwatch sw = Stopwatch.StartNew(); if (!networkDev.Connected) networkDev.Connect("192.168.1.176", 1025); if(networkDev.Connected) networkDev.getReading(); sw.Stop();//Time time taken... }

If the end point is switched on and exists on the network this code works fine (less than a second for whole operation). However should the networked device be switched off or unavailable the AsyncSocket Connect function holds up the main forms thread. Currently if the device is unavailable the whole interface locks up for about 20 seconds (using the stopwatch). I think that I am locking because the main thread is waiting for the return on the Connect request, does this mean I need to put that connect request on another thread?

I have included the code the Async Socket Client I am using -

public bool Connect(String ip_address, UInt16 port) { bool success = false; try { IPAddress ip; success = IPAddress.TryParse(ip_address, out ip); if (success) success = Connect(ip, port); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); } return success; } public bool Connect(IPAddress ip_address, UInt16 port) { mSocket.BeginConnect(ip_address, port, new AsyncCallback(ConnectCallback), mSocket); connectDone.WaitOne();//Blocks until the connect operation completes, //(time taken?) timeout? return mSocket.Connected; } private void ConnectCallback(IAsyncResult ar) { //Retreive the socket from thestate object try { Socket mSocket = (Socket)ar.AsyncState; //Set signal for Connect done so that thread will come out of //WaitOne state and continue connectDone.Set(); } catch (Exception ex) { Console.Out.WriteLine(ex.Message); } }

I was hoping that by using an Async client which has its own thread that this would then stop freezing the interface if the host didn't exist but this does not appear to be the case. After the initial connect failure which takes 20s all subsequent connection attempts are returned immediately (less than a ms). Also something I thought strange, if the initial connection attempt succeeds, any later calls to connect to a non existent host return immediately. A little baffled by what is happening but wondering if its related to the fact that the Socket I use is stored in my AsyncSocket class. Any help much appreciated, if more of the client code is required let me know.

最满意答案

您声称它是异步的,但您的Connect方法显然不是:

mSocket.BeginConnect(ip_address, port, ...); connectDone.WaitOne(); // Blocks until the connect operation completes [...]

你阻塞直到它完成,这是异步行为的对立面。 使用BeginConnect有什么意义,如果你要阻止它连接?

You claim it's asynchronous, but your Connect method clearly isn't:

mSocket.BeginConnect(ip_address, port, ...); connectDone.WaitOne(); // Blocks until the connect operation completes [...]

You're blocking until it's completed, which is the antithesis of asynchronous behaviour. What's the point of using BeginConnect if you're going to block until it's connected?

更多推荐

本文发布于:2023-08-07 06:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1463176.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   客户端   界面   Async   Socket

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!