ThingWorx Edge C SDK > Running the C SDK > Connecting to the Server and Initiating Defined Tasks
  
Connecting to the Server and Initiating Defined Tasks
Connecting to the server first and then initiating tasks is the preferable order, especially if your tasks are pushing data to the server. If you start the tasks earlier, they may attempt to send property updates or invoke services on the server before the connection is established. While reversing the order does not cause any lasting problems, it tends to keep the system very busy with retries before the connection is established.
The connection to the server is attempted and retried with the parameters specified to the twApi_Connect() function. By default, the API automatically reconnects using the same parameters if the connection is subsequently lost. This behavior can be overridden when the API is initialized by setting the autoreconnect parameter to FALSE.
* 
The default setting for DEFAULT_SOCKET_READ_TIMEOUT in twDefaultSettings.h is 500 ms. If a websocket read times out in the middle of reading a record, the SSL state is lost. As a result, the SDK tries to start read the record header again, and the operation fails. To detect this situation, check the log for the SDK for the error, twTlsClient_Read: Timed out after X milliseconds, and consider increasing the value of the DEFAULT_SOCKET_READ_TIMEOUT. You can change the setting at runtime by modifying the value of twcfg.socket_read_timeout.
The API also supports callback notifications when a connection is successfully made and when a connection is lost. The signature for “event callback” functions can be found in the file, src/messaging/twMessaging.h, and the task registration functions are found in the file, twApi.h.
/* Connect to server */
if (!twApi_Connect(CONNECT_TIMEOUT, twcfg.connect_retries)) {
/* Register our "Data collection Task" with the tasker */
twApi_CreateTask(DATA_COLLECTION_RATE_MSEC, dataCollectionTask);
}
Performance Tip - Socket Read Timeout
If you are experiencing slow performance during high traffic C SDK operations, it could be beneficial to decrease the twcfg.socket_read_timeout. This change will allow more blocked threads to access the receive socket to look for the message that they are expecting. While smaller values will lead to increased performance, it is important to keep in mind that the smaller the value of twcfg.socket_read_timeout, the higher the CPU usage. This increased CPU usage should be monitored, especially on power constrained (battery operated, for example) devices.