Solved

Problem with Socket.BeginReceive and WaitHandles

Posted on 2009-05-19
3
1,077 Views
Last Modified: 2013-12-17
Hi All,
I am having problems with asynchronous sockets and wait handles. My system consists of a server and client, with the server notifying the client of updates - the system provides live trading data.
Everything works well using the asynchronous BeginXXX/EndXXX methods on the Socket object, however when my client object connects to the server some data must be queried and calculated before the client object is ready for use. These queries are carried out by sending a request to the server object and waiting for a response. However, as this is done asynchronously I need a mechanism to delay the return of the Connect method until all the queries have been run. I originally tried to accomplish this using AutoResetEvents (see code below).
The problem seems to be that the BeginReceive calls are actually running on the main thread rather than on a ThreadPool one, hence calling WaitOne on my AutoResetEvent blocks the thread and my OnDataReceived callback is never called. Of course, one solution would be to run blocking calls to Receive on a separate thread, but this would seem to contradict the purpose of the BeginXXX/EndXXX methods provided?
I have tried various combinations of WaitHandles/Threads etc but I seem to keep coming up against this issue, any advice would be welcome!
Thanks,
Samuele Armondi
public class Client
    {
        private Socket socket;
        private AutoResetEvent autoResetEvent;
        private IPEndPoint serverEndPoint;
        private byte[] buffer;
 
        public bool Connect()
        {
            //connection code
            socket.Connect(serverEndPoint);
            
            //authentication etc
            
            //start listening for data
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);            
            
            //Run queries
            RunQuery();
 
            //wait for the query to be completed
            autoResetEvent.WaitOne();
        }
 
        private void RunQuery()
        {
            //send data to the socket asking for data
        }
 
        //Async method called when data is received.
        private void OnDataReceived(IAsyncResult res)
        {
            //handle data
 
            //assuming this is the query response, set the AutoResetEvent
            autoResetEvent.Set();
            //carry on receiving
            socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(OnDataReceived), null);            
        }
    }

Open in new window

0
Comment
Question by:peddle
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 3

Expert Comment

by:Kelevra
ID: 24474281
hi,

try that:
//Load 
ThreadPool.QueueUserWorkItem(new WaitCallback(RunQuery), waitHandles[0]);
                ThreadPool.QueueUserWorkItem(new WaitCallback(otherfunction), waitHandles[1]);
                WaitHandle.WaitAll(waitHandles);
 
 
 
//Async method called when data is received.
        private void runQuery(Object state)
        { 
            AutoResetEvent are = (AutoResetEvent)state;
            
            //send data to the socket asking for data
            //handle data
            //slepp in needed
            Thread.Sleep(1000);
 
            are.Set();
        }

Open in new window

0
 
LVL 1

Author Comment

by:peddle
ID: 24474335
Thanks for the suggestion - in this instance it won't work as the reset event needs to be set in the OnDataReceived method.
Many thanks,
S Armondi
0
 
LVL 3

Accepted Solution

by:
Kelevra earned 500 total points
ID: 24474366
0

Featured Post

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Easy filter aspnet 2 36
VB.Net SQL Query 2 Tables Different Databases 3 47
"The resource cannot be found" 1 24
Web page design problem 3 20
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question