DispatcherTimer не отрабатывает событие EventHandler - C#
Формулировка задачи:
Добрый день. Есть небольшая проблема с DispatcherTimer. По какой то непонятной причине не отрабатывается EventHandler с записью данных в СОМ порт, только если вызывать напрямую.
код:
private static SerialPort oSerialPort;
private void btnPush_Click(object sender, RoutedEventArgs e)
{
intcount = 10;
intsec = 5;
while (j <= intcount)
{
fname = "data.txt";
if (j <= intcount)
{
try
{
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, intsec);
dispatcherTimer.Start();
dispatcherTimer_Tick(null, EventArgs.Empty); //ПИШУ РУКАМИ
}
catch
{
}
}
j++;
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (j <= intcount)
{
var indata = File.ReadAllBytes(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fname));
var output = portNo.Text;
oSerialPort = new SerialPort(output);
oSerialPort.BaudRate = 9600;
oSerialPort.Parity = Parity.None;
oSerialPort.StopBits = StopBits.One;
oSerialPort.DataBits = 8;
oSerialPort.Handshake = Handshake.None;
oSerialPort.Open();
oSerialPort.Write(indata, 0, indata.Length);
oSerialPort.Close();
}
}Решение задачи: «DispatcherTimer не отрабатывает событие EventHandler»
textual
Листинг программы
async void btnStress_Click(object sender, RoutedEventArgs e)
{
intcount = int.Parse(count.Text);
intsec = int.Parse(sec.Text);
var tcs = new TaskCompletionSource<object>();
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, intsec);
dispatcherTimer.Start();
// dispatcherTimer_Tick(null, EventArgs.Empty);
while (j <= intcount)
{
if (j <= intcount)
{
try
{
await tcs.Task;
tcs = new TaskCompletionSource<object>();
}
finally
{
dispatcherTimer.Stop();
}
}
else
{
dispatcherTimer.Stop();
}
}
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
if (j <= intcount)
{
j++;
Random rnd = new Random();
int cheque = rnd.Next(1, 23);
fname = "data.txt";
var indata = File.ReadAllBytes(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), fname));
var output = portNo.Text;
oSerialPort = new SerialPort(output);
oSerialPort.BaudRate = 9600;
oSerialPort.Parity = Parity.None;
oSerialPort.StopBits = StopBits.One;
oSerialPort.DataBits = 8;
oSerialPort.Handshake = Handshake.None;
oSerialPort.Open();
oSerialPort.Write(indata, 0, indata.Length);
oSerialPort.Close();
}
}