How Activate a thread via timer? C# .framework 3.5

I have a timer  that has  time interval 5 sec.On timer  tick I want activate a thread.On next timer Tick call the thread function again and so on. Unfortunately , I have problems such as : Timer did not tick again but only once, and I cannot reactivate the thread. Please give me  a solution.
nikavakAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
Please post your code.
0
nikavakAuthor Commented:
private Thread ThreadProcessCoupons;

 public MainForm()
    {
       
        _AnalyzedCoupons = 0;
       
       
        _packetCoupon = 500;//TO BE FROM XML

        try
        {
            InitializeComponent();
            _log = new LogFile();


            ThreadProcessCoupons = new Thread(new ThreadStart(TimerActionprocessCoupons));
         
                       
           
        }
        catch(Exception ex)
        {
            strErrormessage = "Exception on construct main Form : ";
            strErrormessage =strErrormessage + ex.Message;
            _log.Log(strErrormessage);

         }
    }


private void timerAnalyzer_Tick(object sender, EventArgs e)
    {
         ThreadProcessCoupons.Start();
       
       

    }

private void TimerActionprocessCoupons()
    {
         
         _timermessage.Enabled = false;
        _timerAnalyzer.Enabled = false;
        while (_AnalyzedCoupons  <= _packetCoupon)
        {
            ProcessCoupons();

           
        }
        _timermessage.Enabled = true;
        _timerAnalyzer.Enabled = true;
        _secondsDelay = 0;
       
       

   
    }
0
Fernando SotoRetiredCommented:
Hi nikavak;

You have a couple of issues with the code.
(1)  You can not modify the control/components of another thread. You are using a forms Timer control and are attempting to set its state from another thread which is not allowed.

(2) You cannot use the same thread variable without first initializing it as a new thread.

The code snippet below show one way to correct both issues.
using System.Timers;
 
namespace WindowsFormsApplication3
{
    public partial class Form1 : Form
    {
        private Thread ThreadProcessCoupons;
        private int _AnalyzedCoupons;
        private int _packetCoupon;
        private int _secondsDelay;
        // Use a System Timer to get around issue 1
        private System.Timers.Timer _timerAnalyzer = new System.Timers.Timer();
 
        public Form1()
        {
            InitializeComponent();
            _AnalyzedCoupons = 0;
            _packetCoupon = 5;
            _secondsDelay = 0;
 
            // Initialize the System timer to use the method timerAnalyzer as its elapsed event 
            _timerAnalyzer.Elapsed += new ElapsedEventHandler(timerAnalyzer);
            // Set the Interval to 5 seconds.
            _timerAnalyzer.Interval = 5000;
            // Enable the timer
            _timerAnalyzer.Enabled = true;
            
        }
 
        private void TimerActionprocessCoupons()
        {
            Console.WriteLine("Entering thread");
            _timermessage.Stop();
            _timerAnalyzer.Stop();
 
            while (_AnalyzedCoupons <= _packetCoupon)
            {
                ProcessCoupons();
                _packetCoupon--;
            }
 
            _timermessage.Start();
            _timerAnalyzer.Start();
            _secondsDelay = 0;
            Console.WriteLine("Leaving thread");
        }
        
        private void timerAnalyzer(object sender, ElapsedEventArgs e)
        {
            Console.WriteLine("\t\tEntering Timer Tick");
            _packetCoupon = 5;
            // Initialize a new instance of the thread each time to take care of issue 2
            ThreadProcessCoupons = new Thread(new ThreadStart(TimerActionprocessCoupons));
            ThreadProcessCoupons.Start();
            Console.WriteLine("\t\tLeaving Timer Tick");
        }
 
 
        private void ProcessCoupons()
        {
            Console.WriteLine("\t\t\tIn ProcessCoupons");
        }
    }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

KelevraCommented:
Hi,

Here's something that's sometimes used is a hybrid between blocking and spinning:
Cf://I//

The larger x, the more CPU-efficient this is;
 the trade-off being in increased latency. Anything above 20ms incurs a negligible overhead  unless the condition in the while-loop is particularly complex.

Except for the slight latency, this combination of spinning and sleeping can work quite well (subject
to concurrency issues on the proceed flag).



Cf://II//

Hope this'll help!
//I//
while (!proceed) Thread.Sleep (x); // "Spin-Sleeping!"
//or
while(true) Thread.Sleep(x);
 
//II//
//You can block until another thread ends by calling Join:
 
class JoinDemo {
static void Main() {
Thread t = new Thread (delegate() { Console.ReadLine(); });
t.Start();
t.Join(); // Wait until thread t finishes
Console.WriteLine ("Thread t's ReadLine complete!");
}
}

Open in new window

0
nikavakAuthor Commented:
Thanks A lot
0
Fernando SotoRetiredCommented:
Not a problem, glad to help.  ;=)
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.