我有一个线程,有一个循环:
While (IsRunning){
Scan DB
If (having Data) then Enqueue
Else {
Log.Debug("No Data");
Sleep(onePeriod);
}
}
为什么有时候我的线程在睡眠一段时间后没有醒来?
我检查日志(Log by Common.Logging.Log4Net
),当没有数据时,我的线程会定期写入日志,而当其他线程仍在继续运行时突然什么也不做。
请帮我。
我的代码:
while (_isRunning)
{
#region Check if not Online
try
{
if (!Tw2iConfig.IsOnlineEnable())
{
if (Tw2iConfig.CheckShowDebugLoop(ref loopViewTimeIncasOnline))
Log.Debug(string.Format("{0}Check Server online: Time OFFLINE! Sleep {1}ms truoc khi recheck!"
, prefixLog, Tw2iConfig.SleepWhenCheckOnlineIncas));
Thread.Sleep(Tw2iConfig.SleepWhenCheckOnlineIncas);
continue;
}
} catch(Exception ex)
{
Log.Error(string.Format("{0}Check config error", prefixLog), ex);
if (!_isRunning) break;
Thread.Sleep(Tw2iConfig.SleepScanCMSRequest);
continue;
}
#endregion
#region Loop get Data from DB
bool requireSleep = false;
try
{
//Neu ko trong thoi gian Online day => Sleep
var requestDatas = requestDataDal.GetRequestData((int)RequestStatus.NewRequest);
if (requestDatas == null || requestDatas.Count == 0)
{
Log.Debug(string.Format("{0}Query DB: no RequestData(s) found! Sleep {1}ms before re-scan DB!"
, prefixLog, Tw2iConfig.SleepScanCMSRequest));
requireSleep = true;
}
else
{
Log.Info(string.Format("{0}Query DB: found {1} RequestData(s)! Loop & enqueue!"
, prefixLog, requestDatas.Count));
foreach (RequestData requestData in requestDatas)
{
try
{
if (!_isRunning)
break;
// While Queue Full -> no Enqueue more data!!!
DateTime loopView = DateTime.Now;
while (MsgQueue.ShareInstance.IsFull())
{
if (!_isRunning)
break;
if (Tw2iConfig.CheckShowDebugLoop(ref loopView))
Log.Debug(string.Format("{0}Query full, hang Request {2}. Wait & sleep {1}ms"
, prefixLog, Tw2iConfig.SleepQueueFull, requestData.RequestId));
Thread.Sleep(Tw2iConfig.SleepQueueFull);
}
// Add CmsChannel to RequestData to be able to response right!!!
requestData.CmsChannel = cmsChannel;
ProcessOne(requestData);
}
catch (Exception ex)
{
Log.Error(string.Format("{0}Error when wait & enqueue RequestData [Id: {1}]",
prefixLog, requestData == null ? -1 : requestData.RequestId), ex);
}
}
}
} catch(Exception ex)
{
Log.Error(string.Format("{0}Loi query RequestData(s)", prefixLog), ex);
requireSleep = true;
}
#endregion
if (!_isRunning) break;
if (requireSleep)
Thread.Sleep(Tw2iConfig.SleepScanCMSRequest);
}