Task, Thread, Timer, Concept

Markus Freitag 3,786 Reputation points
2023-06-01T16:49:50.59+00:00

Hello,

Loop START ORDER
		Loop
			ProductIn
			ProcessStart
			ProductOut 
			|-------------|------------------------|
		  IN              START                    OUT
Loop END


Buttons
   OrderStart
        In  
		START
		End	  
   OrderEnd

I think I need a userThread a process thread a subwork thread (for asking data from server)

Thread can be a TASK, Timer, or really a thread (BackgroundThread)

How can I implement this, are there any sample examples of how I would need to do this?

Between OrderStart and OrderEnd, 100 to 1000 products pass through the loop. After the state IN I have to request the server, as long as the product is transported mechanically. In the state START the data should be available or output timeout. After OUT state it starts from the beginning.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,634 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 61,416 Reputation points
    2023-06-01T17:58:44.1766667+00:00

    your question is not clear. what do the buttons have to do with the processing? what do you mean by data available? sure OrderStart probably means begin processing (Task.Run()), but what are the others for?

    a button assume a UI, and most UI systems only allow an update to the UI from the UI thread. They typically supply an api to call code on the UI thread. If they don't then typically on the window event loop, you check a semaphore.


1 additional answer

Sort by: Most helpful
  1. Minxin Yu 10,946 Reputation points Microsoft Vendor
    2023-06-07T07:02:54.4366667+00:00

    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; }
    
    }