I wrote a simple logging help class before, copied from another framework, and the test is not easy to use, as follows:
This article reimplements a simple logging class based on BlockingCollection.
BlockingCollection<T> is a thread-safe collection class that provides the following functionality:
Implement the maker-user model. Add and fetch items concurrently through multithreading. Optional maximum capacity. When the collection is empty or full, it is blocked by insert and remove operations. Insert and remove attempts do not block or occur for a specified period of time. Encapsulation implements any collection type of IProducerConsumerCollection<T> Use the cancel tag to perform the cancellation action. Two types of enums that use foreach (in Visual Basic, For Each) are supported: read-only enums. An enumeration that removes an item when an item is enumerated.
Microsoft introduces:The hyperlink login is visible.
BlockingCollection is a thread-safe blocking queue, using this feature to implement the producer-consumer mode within the process, such as message forwarding, logging, etc.
Call its Add method to add information to the queue, and when the queue has no messages, IsCompleted will always block the while loop, so it will not cause a dead loop. When a new message comes out, the IsCompleted in while will be triggered and return the bool type, causing the execution to continue, that is, fetching data from the thread.
Previously, we blocked the thread by calling the WaitOne method of ManualResetEvent, calling the Reset and Set methods to pass the signal, as follows:
The test writes 10,000 logs, which takes less than 10 milliseconds, as shown in the figure below:
The code is as follows:
Source code download:
Tourists, if you want to see the hidden content of this post, please Reply
|