C # Multithreading

Source: Internet
Author: User
Tags thread class

Since the Framework 2.0, multithreading in the thread after the very good encapsulation, management multithreading has become more simple. Now the C # multi-threading knowledge points for management induction.

Use of the thread class: (but the parameter can only be an object class)

Using system;using system.collections.generic;using system.linq;using system.text;using  System.Threading;using System.Threading.Tasks;namespace SampleThread{     Class program    {        static void  main (String[] args)         {             thread noparamthread = new thread (new  ThreadStart (Noparammethod));             thread  hasparamthread = new thread (New parameterizedthreadstart (HasParamMethod));//function with parameters             noparamthread.start ();             hasparamthread.start ("Ainy");//need to pass the reference          &Nbsp;   console.readkey ();        }         private static void noparammethod ()          {            console.writeline (" function without parameters ");        }         Private static void hasparammethod (OBJECT OB)          {            string str = ob  as string;            console.writeline ("Functions  ,  Parameters with Parameters  : {0}"  , str);         }     }}

threadpool (thread pool) class

Using system;using system.collections.generic;using system.linq;using system.text;using  System.Threading;using System.Threading.Tasks;namespace ThreadPoolTest{     class Program    {        static  Void main (String[] args)         {             //threadpool.queueuserworkitem (HasParamMethod,  "Ainy");             threadpool.queueuserworkitem ( Hasparammethod);             console.readkey ();         }        private  Static void hasparammethod (OBJECT OB)        {             string str = ob as string;             console.writeline ("function  ,  parameter with parameters =  : {0}", str);         }    }}


Because there are 2 method overloads for QueueUserWorkItem:

public static bool QueueUserWorkItem (WaitCallback callBack);p ublic static bool QueueUserWorkItem (WaitCallback CallBack , object state);

And WaitCallback is a delegate:

public delegate void WaitCallback (object state);

Therefore,the QueueUserWorkItem parameter method, must take an object parameter, can be null to determine whether the parameter object is valid.


Task (Tasks) class

Task<tresult>: tresult-> return type. Then the task is no return.

Using system;using system.collections.generic;using system.linq;using system.text;using  System.Threading.Tasks;namespace TaskTest{    class Program     {        static void main (String[] args)         {             Task<string> helloTask = new Task<string> (N=>hello (n as  string),  "Ainy");             Hellotask.start ();            task<string>  waitHello = helloTask.ContinueWith<string> (hello => { return  Hello. result +  "  good";  });             Task m = Waithello.continuewith (Wait => console.writeline (Wait). Result));             console.readkey ();         }        private static  string hello (String name)         {             return  "hello , "  + name;         }    }}

About continuewith:task<string> Waithello = hellotask.continuewith<string> (Hello = = {return hello. Result + "good"; })

When the Hellotask execution is complete, the Waithello is executed immediately.


TaskFactory (Task Factory) class

using system;using system.collections.generic;using system.diagnostics;using system.linq; using system.text;using system.threading.tasks;namespace taskfactorytest{     class Program    {        static  Void main (String[] args)         {             stopwatch sw = new stopwatch ();  &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SW. Start ();             list<task> tasks  = new List<Task> ();             taskfactory factory = new taskfactory ();             tasks. ADD (Factory. StartNew (() &NBSP;=&GT;&NBSp Console.WriteLine ("Without Parameters! "));             tasks. ADD (Factory. StartNew (()  => console.writeline ("without parameters! 1 "));             tasks. ADD (Factory. StartNew (()  => console.writeline ("without parameters! 2 "));             //tasks. Add (New task (()  => console.writeline ("xxxxxxxxxxxx"));//Do not add task    in this way                       //the key to adding task ,  in the following way is a start Start method              task newtask = new task (()  => console.writeline (" Xxxxxxxxxxxx "));             tasks. ADD (newtask);          &Nbsp;  newtask.start ();             task  s = factory. Continuewhenany (tasks. ToArray (),  t => console.writeline ("There's a task already done!" "));             task a = factory. Continuewhenall (tasks. ToArray (),  t => console.writeline ("All Tasks are done!") "));             tasks. Add (a);             task.waitall (tasks. ToArray ());             sw. Stop ();             console.writeline ("Total time  {0 } ", &NBSP;SW. Elapsedmilliseconds);             console.readkey () ;         }    }}

Of course, taskfactory<tresult> means a task with a return value.


Use of async/await Keywords

Using system;using system.collections.generic;using system.linq;using system.text;using  System.Threading;using System.Threading.Tasks;namespace AwaitTest{     Class program    {        static void  main (String[] args)         {             noreturnone ();             task<int32> taskreturnint = hasreturn (1, 3);             console.writeline ("important ,  Me In Execution");             console.writeline ("Returned result is  : {0}",  taskreturnint.result);//taskreturnint.result  block the main thread until you get the results             &nbsP Console.WriteLine ("Execution End");             Console.readkey ();        }         /// <summary>        ///  Async async with no return value  void == async task        /// </summary >        private static async void noreturnone ( )         {             console.writeline ("no.1 :  performs a function with no return value");             await task.run (()  => {                 console.writeline (" No.1 :  starts executing asynchronous sub-threads");      &Nbsp;          thread.sleep (;    )             console.writeline ("No.1 :  End asynchronous Child thread ");             });             console.writeline ("no.1  end");         }        /// <summary>         ///  async async task == async void with no return value         /// </summary>         /// <returns></returns>        private  static async task noreturntwo ()         {       &Nbsp;     console.writeline ("no.2 :  performs a function with no return value");             await task.run (()  =>             {                 console.writeline (" No.2 :  Start executing asynchronous child threads");                 thread.sleep (;  )               console.writeline ("No.2  :  End Asynchronous sub-thread ");             });             console.writeline ("no.2  end");         }        /// <summary>         ///  has a return value of         /// </summary>         /// <returns>int32</returns>         private static async task<int32> hasreturn (Int32  a , Int32 b )         {             console.writeline ("no.3 :  performs a function with a return value");             Int32 bc = 0;             await task.run (()  => {                 bc = a  + b;                 thread.sleep (&NBSP;&NBSP;&NBSP);;          });             return bc;        }     }}

The result of the execution is:

650) this.width=650; "Src=" Http://s4.51cto.com/wyfs02/M01/88/EF/wKioL1gBrrvhaRlDAAAnCnjJMHE175.png-wh_500x0-wm_3 -wmp_4-s_3788589516.png "title=" 01.png "alt=" Wkiol1gbrrvharldaaancnjjmhe175.png-wh_50 "/>

As you can see, taskreturnint.result blocks the main thread until it gets the result. Of course, if you go to a bit of an await, but it becomes synchronous.

This article is from the "Better_power_wisdom" blog, make sure to keep this source http://aonaufly.blog.51cto.com/3554853/1862145

C # Multithreading

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.