Click here to Skip to main content
15,915,867 members
Please Sign up or sign in to vote.
1.67/5 (3 votes)
See more:
C#
 private volatile bool _pause = false;
 private ManualResetEvent _pauseEvent = new ManualResetEvent(true);
 private Thread m_thread;
 private bool _istoday = true;
 private bool _isTimer_stop = false;
 private bool _thread_start = true;

private void btn_start_Click(object sender, EventArgs e)
 {

     int timer_interval = (int)numeric_app_freequency.Value;

         timer1_Tick(sender, e);
         timer1.Interval = 60 * 1000 * timer_interval;
         timer1.Enabled = true;
         timer1.Start(); //

 }

 private void timer1_Tick(object sender, EventArgs e)
 {
     if (_thread_start == true)
       {
         _thread_start = false;
         _istoday = true;
         m_thread = new Thread(new ThreadStart(begin_thread));
         m_thread.Name = "thred_1";
         m_thread.IsBackground = true;
         m_thread.Start();

        }

 }

 private void begin_thread()
 {

     int pageNum = 1;

     while (_pauseEvent.WaitOne())
     {
         if (_istoday == true)
         {

             parse_trs(pageNum);
             pageNum++;

         }
         else
         {
             Textbox1.Text = "Work is done"; ;
             break;
         }

     }
     _autoEvent.Set();
 }

 private void parse_trs(int pageNum)
 {
     string str_pageNum = pageNum.ToString();

     string list_url = "http://somedomain.com/bbs/board.php?bo_table=funny&page=" + str_pageNum;

     WebClient client = new WebClient();
     string sourceUrl = client.DownloadString(list_url);

     HtmlAgilityPack.HtmlDocument mydoc = new HtmlAgilityPack.HtmlDocument();

     mydoc.LoadHtml(sourceUrl);


     HtmlNodeCollection tr_col = mydoc.DocumentNode.SelectNodes("/ html / body//div[@id="bo_list"]//table/tbody/tr");

     foreach (HtmlNode node in tr_col)
     {

         _pauseEvent.WaitOne();


         if (post_date == today_date)
         {

             Do work.......................................

         }
         else
         {
             _istoday = false;
             break;
         }

     }
 }


What I have tried:

I have used while loop instead of timer but cpu overloads so the application freez
Posted
Updated 26-Apr-16 5:03am
v10
Comments
Sergey Alexandrovich Kryukov 23-Apr-16 13:58pm    
"it overloads" is not clear.
—SA
hapiten 23-Apr-16 21:53pm    
The cpu overloads and the app freez
Sergey Alexandrovich Kryukov 24-Apr-16 0:19am    
Rephrasing does not add information.
—SA
Philippe Mori 26-Apr-16 20:54pm    
You should first learn how multithreading works before attenting to make a multithreaded program. The above code is poorly written. So it is hard to help you as we would have to rewrite the program anyway.

Just the fact that it overload the CPU is a clear indication that the design is wrong. Where there is nothing to process, you application should not use the CPU.

By the way, you should never access the UI thread controls directly from a background thread.

Also you don't follow the .NET namimg convention.

1 solution

This is probably the worst possibly design for getting some periodic on near-periodic behavior of a thread. There are many reasons for that, no need to discuss them all. The cost of creation of a new thread instance and starting it is one of the factors, but, by far, not the worst. The worst thing is the easy possibility to mess up everything.

Much better straightforward solution would be creation of only one additional thread and keeping it executing during pretty much all of the application lifetime. You simply make it executing in an "infinite" loop (in fact, broken only when the application is about to close) and throttle its activity by using an event wait handle object.

It's important to understand that on the call WaitHandle.WaitOne the thread either passes or is put to a special wait state; it is switched off and never scheduled back to execution until it is waken up, which happens on Thread.Abort, Thread.Interrupt, timeout, and other events, in particular, signalling the wait handle object from another thread. This way, the thread spends zero CPU time in wait state, there is no spin wait, not periodic checks of the state, nothing.

Please see: EventWaitHandle Class (System.Threading)[^].

Please see my past answers:
Making Code Thread Safe[^],
pause running thread[^],
ManualResetEvent and AutoResetEvent in Thread[^],
Running exactly one job/thread/process in webservice that will never get terminated (asp.net)[^].

Pay special attention for the alternative related technique of using a blocking collection; it is unrelated to your immediate question but important to understand.

Now, let's come back to "periodic" repetition by timer. I'm not sure you need it this way. One alternative would be just repeating the piece of code in a thread on its own, taking current real time from, say, System.DateTime.Now, calculation of next execution time and calling Thread.Sleep with appropriate duration. But if you really need a timer (again, I don't know why), its only function would be signaling event wait handle by calling EventWaitHandle.Set(), which wakes up the thread waiting on this event handle instance. Note that this call is thread-safe, unlike almost any other call of some methods. Also note that the timer event happens in some thread you don't know (except really bad System.Windows.Forms.Timer which invokes the tick handler in the UI thread, but this "relief" it its only benefit; in most cases, it should never be used, as the timing is devastatingly bad).

Both techniques solves the biggest problem you may face. What could happen if you start some processing if the processing caused by your previous timer tick is not yet complete? It can be hard to imagine all the possible mess. The solutions I suggest are completely free from this problem.

—SA
 
Share this answer
 
Comments
hapiten 23-Apr-16 21:30pm    
Thank you Sergey.
The foreach loop stops when it crawls list all I didnt put all detail sorce code
I changed the source anyway.
So your solution is not using timer but using blocking collection?
How do I repeat the action every 10 min?
While loop make cpu overloads do I cant use it
Thank you
Sergey Alexandrovich Kryukov 24-Apr-16 0:19am    
I did not say "not using timer but using blocking collection". I offered you two solutions: 1) with timer signaling event wait handle, 2) without timer. I barely mentioned blocking collection, for your education. Please read it all paying some more attention. I also fully explained "how to repeat"; the paragraph starting with "Now, let's come back to "periodic" repetition". Again, Please read it all paying some more attention.
No, while loop does not make CPU "overload". (And there is no such concept.)

The problem if fairly simple, you just need to pay more attention, and work it out accurately.

—SA
hapiten 24-Apr-16 9:07am    
Once again,thank you for your help.
I have added AutoResetEvent instead of timer and used while loop for repedric action.
But the application freeze.
What's wrong with me?
Here is my code


Thank you very much
Sergey Alexandrovich Kryukov 24-Apr-16 20:19pm    
Why using Thread.Sleep and WaitOne? Why both? Use either one of another approach. Also, code in comment is barely readable. If you want to show your code, remove if from comment, add it to the body of the question using "Improve question". Did you run it all under the debugger? Anyway, don't show this very code and don't debug it just yet. Instead, design your code properly, they way you understand each and every line.a

Now, about your code sample. Redesign the code according to your problem. But, instead of trying to develop "real" application, develop only the prototype focusing only on a single technique. Such code could be shown fully here. With the comprehensive code sample simplified to the extreme, it will be easy to find and resolve the problem. By the way, this whole technique is very simple.

—SA
hapiten 25-Apr-16 1:01am    
I improved my question.Please see the updated one thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900