Learning Experience: thread security questions about queue in C #

Source: Internet
Author: User

To ensure the thread security of the queue, all operations must be performed through this package.

Enumeration through a set is essentially not a thread-safe process. Other threads can modify the set even when synchronizing the set, which causes an exception in the number of enumerations. To ensure thread security during enumeration, you can lock the set during the enumeration process or catch exceptions caused by changes made by other threads.

The following example shows how to synchronize the queue, how to determine whether the queue is synchronized, and how to use the synchronized queue.
[C #]
Using system;
Using system. collections;
Public class samplesqueue {

Public static void main (){

// Creates and initializes a new queue.
Queue myq = new Queue ();
Myq. enqueue ("");
Myq. enqueue ("quick ");
Myq. enqueue ("brown ");
Myq. enqueue ("Fox ");

// Creates a synchronized wrapper around the queue.
Queue mysyncdq = queue. synchronized (myq );

// Displays the sychronization status of both queues.
Console. writeline ("myq is {0}.", myq. issynchronized? "Synchronized": "not synchronized ");
Console. writeline ("mysyncdq is {0}.", mysyncdq. issynchronized? "Synchronized": "not synchronized ");
}
}
/*
This code produces the following output.

Myq is not synchronized.
Mysyncdq is synchronized.
*/

By comparing the running results, we can see that the queue packaged by the queue. Synchronized Method is synchronized, and those without packaging are not synchronized. It can be declared at the instantiation,

// Creates a synchronized wrapper around the queue.
Queue mysyncdq = queue. synchronized (New Queue ());

In this way, the synchronization object lock of the queue can be used in a multi-threaded environment to prevent multiple threads from simultaneously writing the queue. To prevent other threads from accessing the queue object, you can use lock (Queue.

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.