views:

31

answers:

1

Hi, thanks in advance for helping.

I want to cancel the AsyncWaitHandle.WaitOne() at some point in my code (meaning I do not want to block anymore), but I just cann't find the way to do it. Perhaps, it is the logical problem of my program, but I can not think of any other way to break out of the loop as soon as exit signal is given. The following is the code which has the problem:

s.Bind(endPoint);  
s.Listen(15);
while (true) {
    thrd = s.BeginAccept(new AsyncCallback(Accept_Callback), s);
    thrd.AsyncWaitHandle.WaitOne(); // it still blocks here when next statement becomde "true"
    if (_syncEvents.ExitThreadEvent.WaitOne(0, false))
    {
       //I want to break out of the loop at this point, it breaks out only when next call coming
        thrd.AsyncWaitHandle.Close();
        s.Close();
        break;
    } 
}

Please help, thanks!

Aaron Chen

+1  A: 

You could use a manual reset event:

    ManualResetEvent evt = new ManualResetEvent(false);

    WaitHandle[] handles = new WaitHandle[] { evt, thrd.AsyncWaitHandle };

    WaitHandle.WaitAny(handles);

Then, from another thread, call:

    evt.Set();

to release the socket.

Paul Keister
Thanks Paul Keister,I will try that and let you know how it is going, thank you!Aaron
AaronChen
Paul,Thanks for solving my problem.Aaron
AaronChen