"C # Multithreaded Programming combat" 2.4 Semaphoreslim

Source: Internet
Author: User

That's a lot easier.

Understanding is also very well understood.

Better understanding than the previous mutex.

What does this Semaphoreslim do?

is to restrict access to the thread. Like saying only two at a time, only three such threads at a time access resources.

It's a bit like a lock method that adds no markup.

First on the code

  classProgram {StaticSemaphoreslim Slim =NewSemaphoreslim (4);//limit the number of threads that are accessed once        Static voidMain (string[] args) {             for(inti =1; I <=6; i++)            {                varName ="thread:_"+i; ints =2+2*i; vart =NewThread (() =Accessdatabase (name, s));            T.start ();        } console.readkey (); }        Static voidAccessdatabase (stringNameintseconds) {Console.WriteLine ($"{name} Waites to"); Slim. Wait ();//Thread WaitsConsole.WriteLine ($"{name} get data");            Thread.Sleep (timespan.frommilliseconds (seconds)); Console.WriteLine ($"{name} is done"); Slim. Release ();//Releasing ThreadsConsole.WriteLine ($"{name} is close"); }    }

This is really good and convenient.

The way of use is also particularly simple.

An instantiation of

Two Waiting threads

Three-release thread

Just so ez.

1    New Semaphoreslim (4); // limit the number of threads that are accessed once 2    Slim. Wait (); // Thread Waits       3    Slim. Release (); // Releasing Threads

This will be understood by a dozen times.

No more talking.

"C # Multithreaded Programming combat" 2.4 Semaphoreslim

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.