Example from past threads: You put the set
at the end of the loop GetDataFromServer
and it causes time out.
Modified :
It allows the start function to run.
// Make work
Thread.Sleep(1000);
StartManualResetEvent.Set();
//State In --> Start the timer and check the data from the server
//State Process --> Check all data here? Timeout --> Cancel it
//State Out --> Stop the TimerThread?
Panel TestPanel = new Panel() { BoardId = "25052023", Mode = Panel.ModePanel.NotDefine, No = 1 };
int Processing = 0;
System.Timers.Timer MyTimer;
double Process;
ManualResetEvent InManualResetEvent = new ManualResetEvent(false);
ManualResetEvent StartManualResetEvent = new ManualResetEvent(false);
ManualResetEvent OutManualResetEvent = new ManualResetEvent(false);
private void btnIn_Click(object sender, EventArgs e)
{
m_cancelTokenSource = new CancellationTokenSource();
StartManualResetEvent.Reset();
// check if running
if (Processing == 1)
{
// notify
return;
}
// start start
Processing = 1;
Task task = Task.Run(() =>
{
GetDataFromServer(1, m_cancelTokenSource.Token);
});
//start watchdog timer
MyTimer = new System.Timers.Timer(500);
// MyTimer.Elapsed += OnTimedEvent;
MyTimer.Elapsed += (s, e2) => elapse(s, e2, "ProductTest");
MyTimer.Elapsed += (s, e2) =>
{
string second = "ProductTest2";
Trace.WriteLine($"Second variant elapsed with :{e2.SignalTime} {second}");
};
MyTimer.AutoReset = true;
MyTimer.Enabled = true;
}
private void btnStart_Click(object sender, EventArgs e)
{
bool currentState = StartManualResetEvent.WaitOne(0);
if (!StartManualResetEvent.WaitOne(5000))
{
m_cancelTokenSource.Cancel();
MessageBox.Show("Timeout");
}
currentState = StartManualResetEvent.WaitOne(0);
}
private void btnOut_Click(object sender, EventArgs e)
{
}
private void btnFinalCancel_Click(object sender, EventArgs e)
{
if (m_cancelTokenSource != null)
m_cancelTokenSource.Cancel();
}
void GetDataFromServer(int serverNumber, CancellationToken token)
{
for (int i = 0; i < 10; i++)
{
try
{
if (token.IsCancellationRequested)
{
Trace.WriteLine("Canceled while running.");
token.ThrowIfCancellationRequested();
}
++TestPanel.No;
// Make work
Thread.Sleep(1000);
StartManualResetEvent.Set();
}
catch (OperationCanceledException)
{
Interlocked.Exchange(ref Process, 0);
Trace.WriteLine("The wait operation was canceled.");
throw;
}
}
Interlocked.Exchange(ref Process, 0);
}
private void OnTimedEvent(Object source, System.Timers.ElapsedEventArgs e)
{
Trace.WriteLine($"The Elapsed event was raised at {e.SignalTime}");
if (Processing == 0)
{
MyTimer.Enabled = false;
// do notification
}
}
public void elapse(object sender, System.Timers.ElapsedEventArgs e, string s)
{
Trace.WriteLine($"elapsed with :{e.SignalTime} {s}");
}
public class Panel
{
public enum ModePanel
{
NotDefine = -1,
Passthrough = 0,
Mark = 1
}
[XmlAttribute("no")]
public int No { get; set; }
[XmlAttribute("mode")]
public ModePanel Mode { get; set; }
[XmlAttribute("BoardId")]
public string BoardId { get; set; }
}