暂无描述

OBInterface.cs 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading;
  6. using System.IO;
  7. using System.IO.Ports;
  8. namespace WpfApplication19
  9. {
  10. public class OBInterface
  11. {
  12. SerialPort _sp;
  13. public OBInterface(SerialPort sp)
  14. {
  15. _sp = sp;
  16. DataSender sender = new DataSender(_sp);
  17. DataReceiver receiver = new DataReceiver(_sp);
  18. Thread pro = new Thread(new ThreadStart(sender.ThreadRun));
  19. Thread con = new Thread(new ThreadStart(receiver.ThreadRun));
  20. try
  21. {
  22. pro.Start();
  23. con.Start();
  24. pro.Join();
  25. con.Join();
  26. }
  27. catch (ThreadStateException e)
  28. {
  29. Console.WriteLine(e);
  30. }
  31. catch (ThreadInterruptedException e)
  32. {
  33. Console.WriteLine(e);
  34. }
  35. }
  36. }
  37. public class DataSender
  38. {
  39. SerialPort _serialPort;
  40. public DataSender(SerialPort sp)
  41. {
  42. _serialPort = sp;
  43. }
  44. public void ThreadRun()
  45. {
  46. while(_serialPort.IsOpen){
  47. Console.WriteLine("Sending");
  48. Thread.Sleep(500);
  49. }
  50. }
  51. }
  52. public class DataReceiver
  53. {
  54. SerialPort _serialPort;
  55. public DataReceiver(SerialPort sp)
  56. {
  57. _serialPort = sp;
  58. }
  59. public void ThreadRun()
  60. {
  61. while (_serialPort.IsOpen)
  62. {
  63. Console.WriteLine("Reading");
  64. Thread.Sleep(500);
  65. }
  66. }
  67. }
  68. class Connector
  69. {
  70. bool _readerFlag = false;
  71. public void ReadFromComPort()
  72. {
  73. lock (this)
  74. {
  75. if (!_readerFlag)
  76. {
  77. try
  78. {
  79. Monitor.Wait(this);
  80. }
  81. catch (SynchronizationLockException e)
  82. {
  83. Console.WriteLine(e);
  84. }
  85. catch (ThreadInterruptedException e)
  86. {
  87. Console.WriteLine(e);
  88. }
  89. }
  90. Console.WriteLine("Reader");
  91. }
  92. }
  93. public void WriteToComPort()
  94. {
  95. }
  96. }
  97. }