Timer-Backgroundworker从另一个backgroundworker-thread调用

时间:2014-06-30 17:46:24

标签: c# timer backgroundworker can-bus

我目前正在开发C#中的CAN技术,以及与消息接收和消息传输有关的方法。到目前为止,我发送的每条消息都正确地传输给消费者,生产者发送的每条消息都将正确地传送给消费者(我)。

每次,一条消息到达receipt-FIFO,_messageReceivedEvent触发器。之后,将开始处理一个或多个接收的消息。在消息处理之后,应该重置现有的计时器(单独的线程)。这意味着,如果5秒内没有消息到达,则不会重置定时器线程,如果经过,则定时器线程应发出信号,表示已经过去,并且应该将一个参数(_isDataCommunicationStillAlive)设置为“FALSE”。 / p>

主线程(调用MessageReceiption-Backgroundworker):

private Timer _commTimer;


public void MessageReceiption()
{
    _quitMessageObservation = false;

    // Generate and call new DataCommunicationTimer as Backgroundworker
    DataCommunicationTimer();

    BackgroundWorker bgWorker = new BackgroundWorker();
    bgWorker.DoWork += ObservingMessageReceiptionFifo;
    bgWorker.RunWorkerCompleted += ObservingMessageReceiptionCompleted;
    bgWorker.RunWorkerAsync();
}


// Observes, if a new message arrived in receiption-FIFO
public void ObservingMessageReceiptionFifo(object sender, DoWorkEventArgs e)
{
    do
    {
      // If a new message arrives in my receiption-FIFO
      if (_messageReceivedEvent.WaitOne(100, false))
      {
         /////// Here would be code, to handle received message(s) ///////

         _isDataCommunicationStillAlive = true;

         // After message receiption, resetting timer should begin.
         // So if no new message arrives within 5 seconds, the 
         // timer counts down, and if elapsed, TimeElapsedEvent
         // should trigger and do some more stuff, like setting 
         // a boolean parameter (_isDataCommunicationStillAlive) 
         // to 'FALSE'.
         RunningDataCommTimer(sender, e);
      }

    } while (_quitMessageObservation == false);

    e.Result = "MessageReceiptionTerminated";
}


private void ObservingMessageReceiptionCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Result.Equals("MessageReceiptionTerminated"))
    {
        Console.WriteLine("Observing message-receiption terminated.");            
    }
}

DataCommunicationTimer (作为Backgroundworker(从MessageReceiption调用)):

public void DataCommunicationTimer()
{
    _commTimer = new Timer();

    // Registers new TimeElapsedEvent
    _commTimer.Elapsed += new ElapsedEventHandler(TimeElapsedEvent);

    BackgroundWorker bgWorker = new BackgroundWorker();
    bgWorker.DoWork += RunningDataCommTimer;
    bgWorker.RunWorkerAsync();
}


public void RunningDataCommTimer(object sender, DoWorkEventArgs e)
{
    while(_isConnected == true)
    {
       // Set the Interval to 5 seconds (5000 milliseconds).
       _commTimer.Interval = 5000;
       _commTimer.Enabled = true;
       _commTimer.Start();
    }
}


public void TimeElapsedEvent(object source, ElapsedEventArgs e)
{
    _isDataCommunicationStillAlive = false;
    _commTimer.Elapsed -= TimeElapsedEvent;
}

问题是,我的Timer-Backgroundworker无法理解,因为它会在一秒钟内终止。另一个问题是,我不知道,如何读出关于剩余时间的特定Timer实例...

根据这些代码行,我找不到bug。 :((

你能帮帮我吗?!

0 个答案:

没有答案