The sharing of three Liezi of Task
This time, I would like to share several columns of C#Task tasks. I feel that the most practical one is the encapsulated paging task execution method, which is also commonly used in multitasking in my work. I don't know if you also have this use, so let's get started.
1. Sequential task execution
View Code
Some words are also noted in the above code, in which the key words and meanings are as follows:
.Task.Factory.StartNew: create a Task instance and start it automatically after creation. There is no need to call Start
.ContinueWith: the meaning of the word is clear, and it means to continue. The effect here is to wait for the last Task to finish execution and then continue to execute this task. Here, each task in the method is passed layer by layer.
Effect picture:
Here is a place to note, sleep this is 5s, but here the use of Stopwatch statistics only 4999ms, there are differences in this place, this chapter does not explain, interested friends can share or study.
two。 Parallel task effect
View Code
The key words and meanings are as follows:
Func is a new feature of C#. The biggest difference between this and Action is that Func has a return value, and other parameters of any length are the same as those of Action.
The .Task.WaitAll method has several overloads. Here we use a timeout method. After setting the time, we will no longer wait for Task [] at the specified time. If the task [] is executed within the timeout range, it will pass directly without waiting for the timeout.
Effect:
There is still statistical time to check the problem, ignore
3. Paging task execution method
View Code
Test the code:
View Code
View Code
What is used here is the principle of paging. Distribute the parameter set to the created Task and use Task [] to deal with the data. Here, if you have some acquaintance with the second example, you only have more paging writing, and finally count the number of successful entries to be returned to the caller to facilitate logging. I often use this method at present. I don't know if there is any better. Thank you.
Effect picture: