After 1.5 days of struggling with DLL and async model I decided to share some 
What I needed is DLL with several functions interacting via sockets with a 
remote app. They must send request messages, receive responces, process them 
and return as out parameters. Function call must be blocking to avoid bugs in 
the host app.
So at first I simply tried MessageLoop inside the function call. But - it's 
running in the main thread's (i.e. thread in host app which called the 
function) context - so it processed all the windows messages to host app like 
Application.ProcessMessages does. Interesting side effect but not usable in my 
Second thing is that I wanted all sockets to be created only on demand so I 
couldn't use its MessageLoop method as I couldn't tell which socket currently 
So I came up to additional thread with its own message loop.
But how could I achieve synchronization between calling functions and thread 
methods? Events? They increased complicateness much. So I had a nice idea: 
SendMessage. It blocks the calling thread while processing is done in the 
context of the window owner. Awesome!
I've done all the stuff and everything seemed good and working when I faced 
with DLLMain.
In my previous version I used some init stuff with no troubles so I thought 
some additional method calls would be OK. Unfortunately DLLMain appeared to be 
a very tricky thing: you can't call methods from other DLLs from there (incl 
GetProcAddress) as they could have not been loaded yet, and no sync methods 
too. But I used them widely to ensure resource cleanup on DLL unload. This 
resulted in deadlock and overall app hang when unloading DLL.
I revised the situation but found only one way: provide special Start/Finish 
methods for init/cleanup. Not a good variant in my case but at least something. 
But the strangest thing is that deadlocks kept happening even when I explicitly 
call Finish before FreeLibrary (btw Finish executes all its commands without 
So I finally got tired of all this stuff and returned to my own simple blocking 
sockets - for DLL and in my case this seems much more applicable. Anyway I 
decided to share my experience - maybe it'll make a little help to someone (I 
really loved that method with SendMessage; things also must be working with 
explicit Start/Finish procedures but they don't and I have no wish to 
investigate why).

Here's demo project I created for testing. It uses OverbyteIcsTcpSrv.exe 
launched on localhost as a server:

P.S. I examined ICS DLL demo but it closes the connection every time - it's not 
an option for me.

To unsubscribe or change your settings for TWSocket mailing list
please goto
Visit our website at

Reply via email to