BeginReceive in a separate thread
For some reason, I need to do BeginReceive on a separate thread, much like this example :
public void WaitForData()
{
Thread t = new Thread(WaitForDataThread);
t.Start();
}
public void WaitForDataThread()
{
try
{
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = m_socClient;
m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, OnDataReceived, theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
But I've always received error right after the BeginReceive call, the OnDataReceived is instantly raised, in that event it will call the EndReceive method, and this error is always thrown : "The I/O operation has been aborted because of either a thread exit or an application request".
But if I remove the separate-thread part (like directly call the WaitForDataThread(), without going through the WaitForData() method), everything works fine.
If you are wondering why would I need to create a separate thread, it is because I need to call the BeginReceive during an event that will be generated from a different thread from a different class. This is pretty much the same like creating a new thread like the sample above, and I need to make it work.
Is there a way that I can 开发者_JAVA技巧do this??
Found the answer on msdn (documentation of Socket.EndReceive):
All I/O initiated by a given thread is canceled when that thread exits. A pending asynchronous operation can fail if the thread exits before the operation completes.
You have to make sure, that your thread where you start your socket-operation does not exit until you are done with your socket I/O.
A workaround is to use a threadpool thread, as described here.
I assume your main thread doesn't wait till the data comes, and simply exits after spawning the other thread. Finishing the main thread kills the whole application, so your WaitForData-thread dies, too.
You have to do the following:
- Start the WaitForData-thread
- Do whatever you want in Main thread
- Wait until the WaitForData-thread finishes in Main thread (Thread.Join?)
- Then exit.
精彩评论