NET Multi-Threading usage

Source: Internet
Author: User

1. Multithreading

2. Thread pool

3.Task

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Windows;usingSystem.Windows.Controls;usingSystem.Windows.Data;usingSystem.Windows.Documents;usingSystem.Windows.Input;usingSystem.Windows.Media;usingSystem.Windows.Media.Imaging;usingSystem.Windows.Navigation;usingSystem.Windows.Shapes;usingSystem.Threading;usingSystem.Diagnostics;namespacemythreads{/// <summary>    ///the interactive logic of MainWindow.xaml/// </summary>     Public Partial classMainwindow:window { PublicMainWindow () {InitializeComponent (); }        Private voidTestMethod () {intsum =0;  for(inti =1; I < -; i++) {sum+=i; } Console.WriteLine ("TestMethod The current thread's id={0},sum= {1}", Thread.CurrentThread.ManagedThreadId, sum); }        Private voidTestthread (stringname) {            intsum =0;  for(inti =1; I < -; i++) {sum+=i; } Console.WriteLine ("{0} id={1},sum= {2} for current thread", Name,thread.currentthread.managedthreadid, sum); }        Private voidBrtthread_click (Objectsender, RoutedEventArgs e) {Console.WriteLine ("This is a single thread");  for(inti =0; I <5; i++) {TestMethod (); }        }        Private voidBrtmutrithread_click (Objectsender, RoutedEventArgs e) {Stopwatch SW=NewStopwatch (); Sw.            Start (); Console.WriteLine ("This is multi-threaded"); Console.WriteLine (string. Format ("id:{0} for the current thread", Thread.CurrentThread.ManagedThreadId)); List<Thread> threadlist =NewList<thread>(); ThreadStart ThreadStart= () + =TestMethod ();  for(inti =0; I <5; i++) {thread thread=NewThread (ThreadStart);                Threadlist.add (thread); Thread.            Start (); } threadlist.foreach (T=T.join ()); Console.WriteLine (string. Format ("Brtmutrithread_click has ended and can perform other actions on the current thread's id={0}", Thread.CurrentThread.ManagedThreadId)); Sw.            Stop (); Console.WriteLine ("total time taken {0}", SW.        Elapsedmilliseconds); }        Private voidBrtthreadpool_click (Objectsender, RoutedEventArgs e) {Stopwatch SW=NewStopwatch (); Sw.            Start (); Console.WriteLine ("This is multi-threaded"); Console.WriteLine (string. Format ("id:{0} for the current thread", Thread.CurrentThread.ManagedThreadId)); //thread Pool//ThreadPool.QueueUserWorkItem (t = testthread ("ThreadPool1")); //ThreadPool.QueueUserWorkItem (t = Testthread (t.tostring ()), "ThreadPool2"); //ThreadPool.QueueUserWorkItem (t = Testthread (t.tostring ()), "ThreadPool3"); //ThreadPool.QueueUserWorkItem (t = Testthread (t.tostring ()), "ThreadPool4"); //ThreadPool.QueueUserWorkItem (t = Testthread (t.tostring ()), "ThreadPool5");            using(ManualResetEvent m1 =NewManualResetEvent (false))            using(ManualResetEvent m2 =NewManualResetEvent (false))            using(ManualResetEvent m3 =NewManualResetEvent (false))            using(ManualResetEvent m4 =NewManualResetEvent (false))            using(ManualResetEvent M5 =NewManualResetEvent (false) {ThreadPool.QueueUserWorkItem (t={Testthread ("ThreadPool1"); M1.                Set ();                }); ThreadPool.QueueUserWorkItem (t={Testthread ("ThreadPool2"); M2.                Set ();                }); ThreadPool.QueueUserWorkItem (t={Testthread ("ThreadPool3"); M3.                Set ();                }); ThreadPool.QueueUserWorkItem (t={Testthread ("ThreadPool4"); M4.                Set ();                }); ThreadPool.QueueUserWorkItem (t={Testthread ("ThreadPool5"); M5.                Set ();                }); M1.                WaitOne (); M2.                WaitOne (); M3.                WaitOne (); M4.                WaitOne (); M5.            WaitOne (); } Console.WriteLine (string. Format ("Brtmutrithread_click has ended and can perform other actions on the current thread's id={0}", Thread.CurrentThread.ManagedThreadId)); Sw.            Stop (); Console.WriteLine ("total time taken {0}", SW.        Elapsedmilliseconds); }

The task essence is based on the thread pool, but the API is hardened
private void Brntask_click (object sender, RoutedEventArgs e)
{
Stopwatch SW = new Stopwatch ();
Sw. Start ();
Console.WriteLine ("Here is multithreading");
Console.WriteLine (String. Format ("Id:{0 of Current thread}", Thread.CurrentThread.ManagedThreadId));
Task
list<task> taskList = new list<task> ();
TaskFactory TaskFactory = new TaskFactory ();
for (int i = 0; i < 5;i++)
{
Tasklist.add (Taskfactory.startnew (() = Testthread ("Task"));
}
Task.waitall (Tasklist.toarray ());


Console.WriteLine (String. Format ("Brntask_click is finished, can perform other actions on the current thread's id={0}",
THREAD.CURRENTTHREAD.MANAGEDTHREADID));
Sw. Stop ();
Console.WriteLine ("Total time elapsed {0}", SW. Elapsedmilliseconds);
}

  

<window x:class= "Mythreads.mainwindow"
xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/ Presentation "
xmlns:x=" Http://schemas.microsoft.com/winfx/2006/xaml "
title=" MainWindow "height=" "Width = "n";
<grid>
<button content= "single thread" height= "horizontalalignment=" "left" margin= "108,63,0,0" Name= "Brtthread" verticalalignment= "Top" width= "page" click= "Brtthread_click"/>
<button content= "Multithreading" Height = "Horizontalalignment=" "left" margin= "108,112,0,0" name= "Brtmutrithread" verticalalignment= "Top" Width= "page" click = "Brtmutrithread_click"/>
<button content= "thread pool" height= "horizontalalignment=" "Left" margin= " 108,168,0,0 "Name=" Brtthreadpool "verticalalignment=" Top "width=" click= "" Brtthreadpool_click "/>
< Button content= "Task" height= "horizontalalignment=" "left" margin= "108,216,0,0" name= "Brntask" verticalalignment= " Top "width=" click= "Brntask_click"/>
</grid>
</window>

NET Multi-Threading usage

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.