DispatcherTimer не отрабатывает событие EventHandler - C#

Узнай цену своей работы

Формулировка задачи:

Добрый день. Есть небольшая проблема с DispatcherTimer. По какой то непонятной причине не отрабатывается EventHandler с записью данных в СОМ порт, только если вызывать напрямую. код:
Листинг программы
  1. private static SerialPort oSerialPort;
  2. private void btnPush_Click(object sender, RoutedEventArgs e)
  3. {
  4. intcount = 10;
  5. intsec = 5;
  6. while (j <= intcount)
  7. {
  8. fname = "data.txt";
  9.  
  10. if (j <= intcount)
  11. {
  12. try
  13. {
  14. System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
  15. dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
  16. dispatcherTimer.Interval = new TimeSpan(0, 0, intsec);
  17. dispatcherTimer.Start();
  18. dispatcherTimer_Tick(null, EventArgs.Empty); //ПИШУ РУКАМИ
  19. }
  20. catch
  21. {
  22. }
  23. }
  24. j++;
  25. }
  26. }
  27. private void dispatcherTimer_Tick(object sender, EventArgs e)
  28. {
  29. if (j <= intcount)
  30. {
  31. var indata = File.ReadAllBytes(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fname));
  32. var output = portNo.Text;
  33. oSerialPort = new SerialPort(output);
  34. oSerialPort.BaudRate = 9600;
  35. oSerialPort.Parity = Parity.None;
  36. oSerialPort.StopBits = StopBits.One;
  37. oSerialPort.DataBits = 8;
  38. oSerialPort.Handshake = Handshake.None;
  39. oSerialPort.Open();
  40. oSerialPort.Write(indata, 0, indata.Length);
  41. oSerialPort.Close();
  42. }
  43. }

Решение задачи: «DispatcherTimer не отрабатывает событие EventHandler»

textual
Листинг программы
  1. async void btnStress_Click(object sender, RoutedEventArgs e)
  2.         {
  3.             intcount = int.Parse(count.Text);
  4.             intsec = int.Parse(sec.Text);
  5.  
  6.             var tcs = new TaskCompletionSource<object>();
  7.  
  8.  
  9.             System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
  10.             dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
  11.             dispatcherTimer.Interval = new TimeSpan(0, 0, intsec);
  12.             dispatcherTimer.Start();
  13.            // dispatcherTimer_Tick(null, EventArgs.Empty);
  14.  
  15.  
  16.             while (j <= intcount)
  17.             {
  18.                
  19.  
  20.  
  21.                 if (j <= intcount)
  22.                 {
  23.                     try
  24.                     {
  25.                        
  26.                         await tcs.Task;
  27.                         tcs = new TaskCompletionSource<object>();
  28.                     }
  29.                     finally
  30.                     {
  31.                         dispatcherTimer.Stop();
  32.                     }
  33.                 }
  34.                 else
  35.                 {
  36.                     dispatcherTimer.Stop();
  37.                 }
  38.                
  39.             }
  40.         }
  41.         private void dispatcherTimer_Tick(object sender, EventArgs e)
  42.         {
  43.             if (j <= intcount)
  44.             {
  45.                 j++;
  46.                 Random rnd = new Random();
  47.                 int cheque = rnd.Next(1, 23);
  48.              
  49.  
  50.                 fname = "data.txt";
  51.  
  52.                 var indata = File.ReadAllBytes(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fname));
  53.                 var output = portNo.Text;
  54.                 oSerialPort = new SerialPort(output);
  55.                 oSerialPort.BaudRate = 9600;
  56.                 oSerialPort.Parity = Parity.None;
  57.                 oSerialPort.StopBits = StopBits.One;
  58.                 oSerialPort.DataBits = 8;
  59.                 oSerialPort.Handshake = Handshake.None;
  60.                 oSerialPort.Open();
  61.                 oSerialPort.Write(indata, 0, indata.Length);
  62.                 oSerialPort.Close();
  63.  
  64.             }
  65.         }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 3.933 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут