0

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

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

主线程(调用 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 无法理解,因为它会在一秒钟内终止。另一个问题是,我不知道如何读出关于剩余时间的特定定时器实例......

基于这些代码行,我找不到错误。:((

请你帮助我好吗?!

4

0 回答 0