Concurrent Threads in C# using BackgroundWorker
- by Jim Fell
My C# application is such that a background worker is being used to wait for the acknowledgement of some transmitted data. Here is some psuedo code demonstrating what I'm trying to do:
UI_thread
{
TransmitData()
{
// load data for tx
// fire off TX background worker
}
RxSerialData()
{
// if received data is ack, set ack received flag
}
}
TX_thread
{
// transmit data
// set ack wait timeout
// fire off ACK background worker
// wait for ACK background worker to complete
// evaluate status of ACK background worker as completed, failed, etc.
}
ACK_thread
{
// wait for ack received flag to be set
}
What happens is that the ACK BackgroundWorker times out, and the acknowledgement is never received. I'm fairly certain that it is being transmitted by the remote device because that device has not changed at all, and the C# application is transmitting. I have changed the ack thread from this (when it was working)...
for( i = 0; (i < waitTimeoutVar) && (!bAckRxd); i++ )
{
System.Threading.Thread.Sleep(1);
}
...to this...
DateTime dtThen = DateTime.Now();
DateTime dtNow;
TimeSpan stTime;
do
{
dtNow = DateTime.Now();
stTime = dtNow - dtThen;
}
while ( (stTime.TotalMilliseconds < waitTimeoutVar) && (!bAckRxd) );
The latter generates a very acurate wait time, as compared to the former. However, I am wondering if removal of the Sleep function is interferring with the ability to receive serial data. Does C# only allow one thread to run at a time, that is, do I have to put threads to sleep at some time to allow other threads to run?
Any thoughts or suggestions you may have would be appreciated. I am using Microsoft Visual C# 2008 Express Edition. Thanks.