Chilkat Socket Thread-Safety

Question:

In my Visual FoxPro program, accessing the IsConnected property on a ChilkatSocket hangs when a “ReceiveUntilByteBdAsync” is run immediately after connecting the socket.

Here is a minimal reproducible example:

LOCAL loSocket
loSocket = CreateObject('Chilkat_9_5_0.Socket')
loSocket.connect('127.0.0.1', 8945, .f., 5000)  &&used external socket server to be sure it was unrelated
 
loBinData = CreateObject('Chilkat_9_5_0.BinData')
loTask = loSocket.ReceiveUntilByteBdAsync(ASC('Z'), loBinData)
?loSocket.IsConnected &&works
loTask.run()
?loSocket.IsConnected &&hangs
return

Answer:

All Chilkat objects are thread-safe.  This means only as single thread can be in a Chilkat method or property call at a time.  When you call the Async method, there is a background thread (managed by Chilkat) that is making the call to loSocket.ReceiveUntilByteBd.  Therefore, your foreground thread’s simultaneous access to the loSocket.IsConnected property is blocked until the ReceiveUntilByteBd method in the background thread completes.

However, the Chilkat Socket object has a feature to allow finer-grained thread safety.  For example, if you wish to read and write from the same socket simultaneously from separate threads.  You can accomplish this by using Socket.CloneSocket.

For example:

LOCAL loSocket
LOCAL loFgSocket
LOCAL lnIsConnected

loSocket = CreateObject('Chilkat_9_5_0.Socket')

loFgSocket = loSocket.CloneSocket()
* ...

lnIsConnected = loFgSocket.IsConnected
* ...

RELEASE loSocket

When you clone a Chilkat socket object, you get a new Chilkat Socket that shares the same underlying connection.  Therefore, the object-level thread safety feature won’t block the call to IsConnected, because technically it’s a different Chilkat object.   The IsConnected property access should be allowed to happen at the same time as the background thread is reading the socket.

Cloning a socket allows you to simultaneously do different things on a single socket connection.  However, you still can’t simultaneously read a socket from two threads — it obviously makes no sense.  Likewise, you cannot simultaneously write to a socket from two separate threads.  But you can write from one thread and read from another.  Or check the connectivity from a thread while reading/writing from another.

 

Tags :