Original article address:
Http://www.cnblogs.com/adaiye/archive/2011/10/25/WPF-MongoDB-Fan-Thread.html
Presumably, as children's shoes know, when performing time-consuming operations (such as crawling and analyzing website data here), if the thread is not used for execution, the interface will be suspended.
To solve this problem,. NET will provide us with a lot of tools to handle multiple threads. backgroundworker is one of them. It encapsulates all the multi-thread processing and is convenient for applications.
Simple to use. Define a backgroundworker
View sourceprint?
Private Backgroundworker BW = New Backgroundworker (); |
Then define its dowork and runworkercompleted events. To report the progress, you can also handle the processchanged event.
Bw. dowork + =NewDoworkeventhandler (bw_dowork );
Bw. runworkercompleted + =NewRunworkercompletedeventhandler (bw_runworkercompleted );
We put time-consuming operations (crawling and analyzing website data) in bw_dowork:
Private VoidBw_dowork (ObjectSender, doworkeventargs E)
{
E. Result = getdata ();
}
Then display the data in the completed event. When displaying the data, note that the control cannot be accessed across threads due to multithreading. Therefore, you need to use dispatcher to call the delegate:
Private VoidBw_runworkercompleted (ObjectSender, runworkercompletedeventargs E)
{
This. Dispatcher. begininvoke (NewAction () =>
{
List AsList Rgv. itemssource =Null;
Rgv. itemssource = listh;
}));
}
OK. The preceding Code uses a thread to obtain data.
However, in many cases, we want to allow crawlers to crawl every other time, instead of only once, or when users trigger them manually. Therefore, we need an alert clock (timer) to notify crawlers of the job.
Therefore, we define another Timer:
View sourceprint?
Private Dispatchertimer timer = New Dispatchertimer (); |
Set the time interval of a timer and the tick event:
View sourceprint?
Timer. Tick + = New Eventhandler (timer_tick ); |
Timer. interval = New Timespan (0, 5, 0 ); // Five minutes |
Then, the crawler is notified in the tick event:
Private VoidTimer_tick (ObjectSender, eventargs E)
{
If(! Bw. isbusy)//If the worker is still running when isbusy = true, the backgroundworker reports an exception.
{
Bw. runworkerasync ();
}
}
The final attachment is executable.ProgramFor everyone to make bricks ~ Real Estate Information Collector
Next, I will add the MongoDB database and add the downloaded data to the database ~~~~~