Java attack c#--syntax of multi-threading

Source: Internet
Author: User

This chapter is a brief statement

In the previous chapter, the author of C # some unique syntax points to explain, I believe you can see some of the magic of C #. Then this chapter is mainly in the multi-threaded knowledge. Whether it is C # or Java, the development process will be more or less used for multithreaded programming. Of course, the author can not be multi-threaded knowledge point to speak very comprehensive. I'm just talking about some of the things I used to do here. If you are interested in friends, I hope that the initiative to find information.

Thread class

It's no stranger to the thread class who believes in Java. At a point, C # is similar to Java. There is a certain difference in use. The first thing to understand is that the multithreading capabilities of C # are generally named under the empty system.threading. As for what is a thread, the process is something like that. I will not say much. I believe we all understand. I prefer a direct point. Let's take a look at the code to learn it.

C#:

1  Class Program 2     {3         static void Main (string[] args) 4         {5             thread myThread1 = new Thread (() = 6
   {7                 Console.WriteLine ("This is a lambda expression creation thread"), 8             }), 9             thread myThread2 = new Thread (THREADSTARTIMP); 11 The thread             myThread3 = new Thread ((object obj) =>13             {                 Console.WriteLine ("This is a lambda expression that creates a parameter with parameters:") + obj. ToString ()); Mythread1.start ();             Mythread2.start ();             Mythread3.start ("Aomi"); }22 public         static void Threadstartimp ()             26 ("This is a method of creating threads");         }27     }

The author creates three threads of code above. MyThread1 and myThread2 are the same thread. That is, a thread without parameters. The MYTHREAD3 is a thread with parameters. Whether there are parameters or not. It is basically the same way. If there are arguments, it is the time to call the Start method to pass in a parameter. We can see that there is a big difference between the use and Java. Java's thread class constructor parameters are passed into the Runnable interface. Unfortunately, C # is not. The following code.

C#:

Public Thread (parameterizedthreadstart start);p ublic thread (threadstart start);p ublic thread ( Parameterizedthreadstart start, int maxstacksize);p ublic Thread (threadstart start, int maxstacksize);

This code is inside the source. Check the thread class by F12 to see the structure of the thread class. We can see four constructors. We often use only two: Thread (parameterizedthreadstart start) and thread (ThreadStart start). When I just saw it, I always thought ThreadStart would look like Java's runnable interface. Only to press F12 enter to look at the structure to understand the wrong. The following code

C#:

[ComVisible (true)]public delegate void ThreadStart ();

C#:

[ComVisible (false)]public delegate void Parameterizedthreadstart (object obj);

We can clearly see a keyword delegate. I believe that a friend who has seen the last chapter knows that he is related to the incident. Nothing wrong. is to define a delegate type. In order to be used in future methods. So we can understand that the parameters of the constructor of the thread class here can only be passed to the method. Then believe that the author above the definition of the three threads is also very obvious significance.

MyThread1 Threads: The author uses lambda expressions to create. What is lambda expression? The previous chapter also has a brief talk.

MyThread2 Thread: Outside defines a method for implementing multithreading. This method can be a static method or a method that can be an object. The function of the keyword static looks like java.

MYTHREAD3 Thread: The implementation has a multithreaded with parameters.

The above is just about the use of the thread class. For some of the methods in the thread class object, I will not introduce more. As large as the Java thread class. such as the interrupt method. Readers are invited to view them on their own.

ThreadPool class

When we talk about the multi-threaded pool, I believe we all know what it is. C # uses the ThreadPool class. It's just a pity that I don't have much chance to use multithreaded pool on Java side. So it's unclear how much the Threadpoolexecutor class and executors class in Java differ from the ThreadPool class in C #. But interested friends can have a look. I am here to talk about the use of ThreadPool class. The ThreadPool class is a bit more like a tool class. As in the code below.

C#:

Class program    {        static void Main (string[] args)        {            threadpool.queueuserworkitem ((obj) + =            {                Console.WriteLine ("This is a lambda expression that creates parameters for a thread parameter:" + obj.) ToString ());            });            ThreadPool.QueueUserWorkItem (Waitcallbackimp);        }        public static void Waitcallbackimp (Object obj)        {            Console.WriteLine ("This is a method of creating threads");        }    }

The above code is a bit like the thread class above. But there is a big difference in nature. This is a multi-threaded pool. Also for multi-threaded pool settings. As long as the threadpool.xxxxx inside there are many ways for you to set.

Task class

If you use the thread class above you will find that sometimes it is difficult to stop when the thread is running. But if you use the task class, you will find that the difficulty is no longer there. I'm not sure why C # introduces a task class. Maybe it's because the thread class and the ThreadPool class are too difficult to control. Then this is not the problem I am concerned about. Let's take a look at how the task class is used. Task classes are often called tasks in Chinese. So there is a saying. is a single or multi-tasking. Why do I say this? As follows.

1. Single task. That is, an instance of a task class. This time is relatively simple. The code is as follows

  Class program    {        static void Main (string[] args)        {            CancellationTokenSource cts = new CancellationTokenSource ();//used to cancel            a task MyTask = new Task ((obj) =            {                Console.WriteLine ("This is a single task");            } , CTS);            Mytask.start ();            Console.readkey ();        }    }

In this, the author only used a class CancellationTokenSource. This class is used to cancel a task. or let the author write an example of it.

Class program    {        static void Main (string[] args)        {            CancellationTokenSource cts = new CancellationTokenSource ();//used to cancel            a task MyTask = new Task ((obj) =            {                                Console.WriteLine ("This is a single task");                Thread.Sleep (20000);//Let him sleep for some time            }, CTS);            Mytask.start ();            if (CTS. iscancellationrequested)//Determine if            {                cts is canceled. Cancel ();            }            Console.readkey ();        }    }

2. Multi-tasking. is an instance of multiple task classes to mate with. This is the time for someone to do it first. Who did after the problem.

Class program    {        static void Main (string[] args)        {            CancellationTokenSource cts1 = new CancellationTokenSource ();//used to cancel            a task MyTask1 = new Task ((obj) =            {                                Console.WriteLine ("This is a single task");                Thread.Sleep (20000);//Let him sleep for            a while}, cts1);            CancellationTokenSource cts2 = new CancellationTokenSource ()//used to cancel            mytask1.continuewith (Task) = {                Console.WriteLine ("MyTask2 task")            , Cts2. Token);            Mytask1.start ();            if (cts1. iscancellationrequested)//Determine whether to cancel            //{            //    cts1. Cancel ();            }            Console.readkey ();        }    }

The ContinueWith method above means: When the MyTask1 is finished, you can continue with the red code. That is another task. In addition to the above example, there is another use. The code is as follows.

CancellationTokenSource cts3 = new CancellationTokenSource ()//For canceling Task.Factory.StartNew ((obj) =>{   Console.WriteLine ("This is a factory single task");}, CTS3);

I don't have to say much about it. There is a point similar to the concept of multithreaded pools. Just note that there are some very useful features in task.factory. The Continuewhenall method is a good embodiment. And the continuewith above have a like. That is, the end of the task is executed before the corresponding last task executes. Please use task.factory. Let him tip to learn. If you are not prompted, finish writing the "Ask" above. Factory. " Then press CTRL+J. There are various ways for you to learn.

This chapter summarizes

This chapter is mainly about multithreading commonly used to explain some of the knowledge. The author did not explain them in detail. So I hope readers can continue to go deep according to the author's words.

Java attack c#--syntax of multi-threading

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.