[英]Executing an asynchronous socket on a background thread
I have been having playing with implementing some socket code to see if it fits my needs and so use the sample code @spender kindly added to this question . 我一直在尝试实现一些套接字代码,以查看它是否符合我的需求,因此请使用示例代码@spender友好地添加到此问题中 。
If I run this on the main thread it works as expected but when I invoke it on a background thread it never gets awoken from its sleep when a client attempts to connect, my thread spawn is as below: 如果我在主线程上运行它,则按预期运行,但是当我在后台线程上调用它时,如果客户端尝试连接它,它就永远不会从睡眠中唤醒,我的线程生成如下:
_Thread = new Thread(new ThreadStart(StartListening));
_Thread.Name = "ThreadForSocket";
_Thread.IsBackground = true;
_Thread.Start();
private void StartListening()
{
new AsyncSocketListener().StartListening(InitializeEndPoint());
}
public class AsyncSocketListener : IDisposable
{
public void StartListening(IPEndPoint endPoint)
{
try
{
var socket = new Socket(endPoint.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(endPoint);
socket.Listen(10);
while (true)
{
string info = string.Format("{0} Waiting for a connection...", DateTime.Now.ToString("HH:mm.ss"));
Controller.StatusSignal.Reset();
Console.WriteLine(info);
Debug.WriteLine(info);
socket.BeginAccept(new AsyncCallback(SocketListener.AcceptCallback), socket);
Controller.StatusSignal.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("Closing the listener...");
}
The thread is still present in the Threads Window and is in the expected state so I'm at a loss as to why it refuses to wake up on client connection. 该线程仍然存在于“线程窗口”中,并且处于预期状态,因此我对为什么拒绝在客户端连接上唤醒感到困惑。
Should that be possible? 那有可能吗? I read the socket msdn page and it appears to suggest it should be OK for a background thread.
我阅读了套接字msdn页,它似乎表明它对于后台线程应该可以。
(After too much hair-pulling and a process of elimination) (经过过多的拔毛和消除过程)
The code is fine, (Windows) Firewall had blocked the binary using the background thread (without notifying, despite its settings) but had allowed the non-threaded version thru, hence why I originally thought it was a code issue. 代码很好,(Windows)防火墙已使用后台线程阻止了二进制文件(尽管已设置,但未通知),但允许使用非线程版本,因此我最初认为这是代码问题。
So, yes, the async pattern shown above is perfectly fine running on a background thread as shown, and of course its quite a nice way of using it as you are simply sleeping the bg thread and your main (eg. UI) thread can operate normally. 因此,是的,上面显示的异步模式在后台线程上运行非常好,如图所示,当然,它是使用它的一种很好的方式,因为您只是在休眠bg线程并且您的主线程(例如UI)可以运行一般。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.