C # implement producer and consumer queues,

Source: Internet
Author: User

C # implement producer and consumer queues,

In the development process, we often encounter a scenario where we need to obtain some data from a place, process the data, and save it in the database.

Private void FetchData () {} private void SaveData () {} static void Main (string [] args) {for (int I = 0; I <10; I ++) {FetchData (); // obtain the data SaveData (); // process and save }}

For example, if the preceding code example is executed sequentially, the execution will be slow because the process of obtaining data and processing and saving may cause blocking. However, FetchData () you do not need to wait until the previous data is saved.

This scenario is very suitable for producer consumer Queues: the producer is FetchData (), used to produce data, and the consumer SaveData () is used to consume data.

For example, we need to use a Web Api to obtain the weather conditions of some cities and save them to the database.

Implementation Method:

The complete implementation code is as follows:

Class Program {// task Queue static Queue <string> _ tasks = new Queue <string> (); // to ensure thread security, use a lock to protect _ task access readonly static object _ locker = new object (); // send a signal to the working thread through _ wh static EventWaitHandle _ wh = new AutoResetEvent (false ); static Thread _ worker; static void Main (string [] args) {// the city code var cityIds = new List <int> {101280601,101 010100, 101020100,101 110101, 101040100}; // start the job thread _ Worker = new Thread (Work); _ worker. start (); // The producer inserts the data into the team and sends the foreach (var cityId in cityIds) EnqueueTask (FetchData (cityId) to the working thread )); // Dispose ();} // <summary> execute the Work </summary> static void work () {while (true) {string Work = null; lock (_ locker) {if (_ tasks. count> 0) {work = _ tasks. dequeue (); // if (work = null) when a task exists: When a null task is encountered, return is returned ;}} if (work! = Null) SaveData (work); // when the task is not null, else _ wh is processed and saved. waitOne (); // no task, wait for signal} // <summary> insert task </summary> static void EnqueueTask (string task) {lock (_ locker) _ tasks. enqueue (task); // insert task _ wh to the queue. set (); // send a signal to the working thread} // <summary> end release </summary> static void Dispose () {EnqueueTask (null ); // insert a Null task to notify the worker thread to exit _ worker. join (); // wait for the worker thread to finish _ wh. close (); // release resources} // <summary> obtain data </summary> static string FetchData (int cityId) {var wc = new WebClient {Encoding = Encoding. UTF8}; var url = string. format ("http://www.weather.com.cn/adat/sk/%0%.html", cityId); return wc. downloadString (url) ;}/// <summary> process and save </summary> static void SaveData (string data) {var weatherInfo = (JsonConvert. deserializeObject (data, typeof (Dictionary <string, Weatherinfo>) as Dictionary <string, Weatherinfo>) ["weatherinfo"]; Console. writeLine ("[{0}]: {1} temperature ({2}) wind direction ({3}) Wind Power ({4})", weatherInfo. time, weatherInfo. city, weatherInfo. temp, weatherInfo. wd, weatherInfo. ws); Thread. sleep (200); // Save the simulated data} public class Weatherinfo {public string City {get; set;} public string Temp {get; set;} public string Time {get; set;} public string Wd {get; set;} public string Ws {get; set ;}}}

Explanation:

 

Reference: Threading in C # --> Chinese Translation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.