C # thread-fourth thread instance,

Source: Internet
Author: User

C # thread-fourth thread instance,

Overview

In the previous sections, I have shared some basic usage methods of threads. In this chapter, I will write some Application Instances in daily development based on my previous discussions, and pay attention to writing multithreading. If you have any good examples, please share them ..

 

Application Instance
Application: scheduled task program

Scenario: there are usually some stored procedures or methods that need to be periodically and cyclically executed in the system. In this case, a scheduled task applet appears.

Model: Query scheduled tasks to be periodically executed --> insert thread pool --> execute tasks

Static void MainMethod () {Thread thead; thead = new Thread (QueryTask); thead. isBackground = true; thead. start (); Console. read () ;}/// <summary> /// query scheduled tasks /// </summary> static void QueryTask () {TaskModel todo_taskModel; while (true) {int count = new Random (). next (1, 10); // Number of simulated task records generated for (int I = 0; I <count; I ++) {todo_taskModel = new TaskModel () {TaskID = I, ITime = DateTime. now}; ThreadPool. queueUserWorkItem (InvokeThreadMethod, todo_taskModel);} Thread. sleep (30000 ); // 30 s for one cycle }}/// <summary> // complete the scheduled task /// </summary> /// <param name = "taskModel"> </param> static void InvokeThreadMethod (object taskModel) {TaskModel model = (TaskModel) taskModel; Console. writeLine ("execution task ID: {0 }...... execution completed. {1} ", model. taskID, model. ITime) ;}/// <summary> /// task entity /// </summary> class TaskModel {public int TaskID {get; set;} public DateTime ITime {get; set ;}}

1. when querying a scheduled task, the task is pushed to the thread pool without waiting for the task to be completed in the thread pool. (to avoid some scheduled tasks taking a long time and blocking the execution time of subsequent scheduled tasks) loop the scheduled tasks every 30 seconds.

2. Print the corresponding information after each scheduled task is completed. (logs can also be recorded)

3. If the number of queried scheduled task records is large, you can adjust the cycle interval accordingly. This prevents the task from being inserted into the thread pool for too long to block the subsequent scheduled task execution time.

Application: Data push Program

Scenario: in our daily system, a lot of interface data needs to be pushed to a third-party platform in real time (for example, a change in member information is pushed to the platform ..). In this case, we need to write some data push programs.

Model: search task --> insert thread pool --> wait until the thread pool task is completed --> prompt that the task is completed

Static void MainMethodB () {Thread thread = new Thread (QueryTaskB); thread. IsBackground = true; thread. Start ();}
Static void QueryTaskB () {ManualResetEvent [] manualReset; TaskModeB model; while (true) {int RandomNumber = new Random (). next (0, 6); manualReset = new ManualResetEvent [RandomNumber]; for (int I = 0; I <RandomNumber; I ++) {manualReset [I] = new ManualResetEvent (false); model = new TaskModeB () {TaskId = I, ITime = DateTime. now, manualResetEvent = manualReset [I]}; ThreadPool. queueUserWorkItem (InvokeThreadMethodB, model);} // wait for the thread pool task to complete ManualResetEvent. waitAll (manualReset); Console. writeLine ("the thread pool task has been completed. completion Time: {0} ", DateTime. now); Thread. sleep (30000) ;}} static void InvokeThreadMethodB (object obj) {TaskModeB model = (TaskModeB) obj; Thread. sleep (1, 1000); Console. writeLine ("execution task ID: {0}, execution time: {1}, completion time: {2}", model. taskId, model. ITime, DateTime. now); model. manualResetEvent. set ();} class TaskModeB {public int TaskId {set; get;} public DateTime ITime {set; get;} public ManualResetEvent manualResetEvent {set; get ;}}

QueryTaskB () records the number of task records after retrieving the number of task records, instantiate the corresponding ManualResetEvent array, and send it as a parameter to the thread task in the thread pool.

Wait until all tasks in the thread pool are completed. You can write your own business logic as needed.

 

Differences between the two instances: whether to wait for all tasks in the thread pool to complete.

In instance 1, scheduled tasks have high requirements on the execution time and must be executed at a certain time point. Therefore, tasks in the thread pool cannot be completed.

Disadvantage: If a task exists, it is inserted into the thread pool. Some tasks may be executed for a long time, and the thread pool repeats every 30 seconds, in the end, many long-time tasks in the thread pool are not completed. When the number of threads in the thread pool reaches 1023 (the default maximum number of threads in the thread pool), the thread pool will not create a new number of threads to complete new tasks, you can only wait for the number of threads in the current thread pool to be released.

In instance 2, the data pushing program has a lower requirement on the push time than in instance 1. The interface table is pushed to a third-party platform as long as the data is retrieved. Generally, the amount of data transmitted each time is not large, but it is very frequent.

Disadvantage: When the push data volume is large, the task execution time may be long. The main thread waits for all tasks in the thread pool to complete. The interval between all cyclic search tasks may be 30 S + NS.

 

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.