As we all know, when performing time-consuming operations (for example, crawling and analyzing website data ),Background threadThe interface will be suspended.
To solve this problem,. NET will provide us with a lot of solutions.Background threadThe backgroundworker tool is one of them. It encapsulates all the thread processing and is convenient for applications.
Simple to use. Define a backgroundworker
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. When capturing data, we should note that the control cannot be accessed across threads due to multithreading, therefore, if you want to operate interface controls, you need to use dispatcher to call the delegate:
Private VoidBw_dowork (ObjectSender, doworkeventargs E)
{
E. Result = getdata ();
}
Then display the data in the completed event:
Private VoidBw_runworkercompleted (ObjectSender, runworkercompletedeventargs E)
{
List AsList Rgv. itemssource =Null;
Rgv. itemssource = listhi;
}
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:
Private dispatchertimer timer = new dispatchertimer ();
Set the time interval of a timer and the tick event:
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 ~~~~~
Develop real estate information collectors with WPF + MongoDB (1)