curs .net 8-9.pdf

Upload: andera4u

Post on 14-Apr-2018

252 views

Category:

Documents


1 download

TRANSCRIPT

  • 7/27/2019 curs .NET 8-9.pdf

    1/30

    !

    "!

    !#$!

    %&!!!!"!

    "!

    !"$!

    %&!!

    !!"!

    !!

    !

    '( )!&

    "# !!!"

    &!"$%!"!

    #$!( !!!&&!!*!&!

    !!"$

    !&! +!$

    !" !!!&&!

    !"!!"!

    ! !!

    ! !!!&&!!&!&

    & !!"&$!,-&

    "!!!

    !# !!!&&!!!#!!

    +$!"!

    !!!"!

    "# $."/

    !&!

  • 7/27/2019 curs .NET 8-9.pdf

    2/30

    (+ )!!.&,.!

    $

    %- $!"!&!!

    $!'01-2()&!!

    -++" !""$

    $&!,-

    !!

    !3 !!!&!

    !!

    !# !!!

    !!

    +" !!!!

    '+" "!"

    "$!!

    '-+" !"&!

    '3

    # #!!!$ #!!$

    !

    !# #!!

    +"#$-"/

    [Visual Basic]

    NotInheritable Public Class Thread[C#]

    public sealed class Thread

    [C++]

    public __gc __sealed class Thread

    [JScript]

    public class Thread

  • 7/27/2019 curs .NET 8-9.pdf

    3/30

    '

    45

    4+( %

    4#

    6

    6# '#7

    6'" '#7

    67 '#7

    # #*

    6# #

    " "*6" #

    4. #

    +"

    (

    !!! 189

    ) !!"!!"!!"!!!$!

    #$!!"!&

    :1;

    *+ !!""

    !!!"$!!

  • 7/27/2019 curs .NET 8-9.pdf

    4/30

    &

    !+ &!

    &&

    #?!!!

    ++ ?!&!!!!

    ++ ?!!!

    + ?!!@."$

    +! ?!$!

    +4+ ?!"$!.

    - ?!!!

    -*+ ?&!!!

    "!

    -&?&!!!"

    !!

    % ?!!!

    $ ?!!$

    !

    !# ?!!!

    &

    " -!"!

    !&!!"!

    !!+!!$!!

    )# !!

    %)# !

    * (inherited from Object) -)&!!&-"/*

    6%)# !"&!!

    ?) !!!!&!!!@

    ?) !&!!!!

    ?)) *

    ?3!+ (inherited fromObject)

    #!!$

    "!!!!!"

    ?%)# (

    ?$ (inherited from Object) ?!$!

  • 7/27/2019 curs .NET 8-9.pdf

    5/30

    - !!!",!

    , -

  • 7/27/2019 curs .NET 8-9.pdf

    6/30

    public function Thread(

    start : ThreadStart

    );

    &4!#

    % !.2

  • 7/27/2019 curs .NET 8-9.pdf

    7/30

    #!"!#

    [Visual Basic]

    Public Sub Start()

    [C#]345[C++]

    public: void Start();

    [JScript]

    public function Start();

    !# !!!$"

    #$ ! ! !

    #$

    --$ ! ! $ " !

    !% !!&!!

    .2

  • 7/27/2019 curs .NET 8-9.pdf

    8/30

    }

    }

    }

    ,

    [C#]

    using System;

    using System.Threading;

    // Simple threading scenario: Start a static method running

    // on a second thread.

    public class ThreadExample {

    // The ThreadProc method is called when the thread starts.

    // It loops ten times, writing to the console and yielding

    // the rest of its time slice each time, and then ends.

    public static void ThreadProc() {

    for (int i = 0; i < 10; i++) {

    Console.WriteLine("ThreadProc: {0}", i);

    // Yield the rest of the time slice.

    Thread.Sleep(0);

    }

    }

    public static void Main() {

    Console.WriteLine("Main thread: Start a second thread.");

    // The constructor for the Thread class requires a ThreadStart

    // delegate that represents the method to be executed on the

    // thread. C# simplifies the creation of this delegate.

    Thread t = new Thread(new ThreadStart(ThreadProc));

    // Start ThreadProc. On a uniprocessor, the thread does not get// any processor time until the main thread yields. Uncomment

    // the Thread.Sleep that follows t.Start() to see the difference.

    t.Start();

    //Thread.Sleep(0);

    for (int i = 0; i < 4; i++) {

    Console.WriteLine("Main thread: Do some work.");

    Thread.Sleep(0);

    }

    Console.WriteLine("Main thread: Call Join(), to wait until

    ThreadProc ends.");

    t.Join();

    Console.WriteLine("Main thread: ThreadProc.Join has returned.

    Press Enter to end program.");

    Console.ReadLine();

    }

    }

  • 7/27/2019 curs .NET 8-9.pdf

    9/30

    &6"

    ,-

    #$-"/

    &[Visual Basic]

    NotInheritable Public Class ThreadPool

    [C#]

    public sealed class ThreadPool

    [C++]

    public __gc __sealed class ThreadPool

    [JScript]

    public class ThreadPool

    & "

    #5

    C2

  • 7/27/2019 curs .NET 8-9.pdf

    10/30

    public static void Main() {

    // Queue the task.

    ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

    Console.WriteLine("Main thread does some work, then sleeps.");

    // If you comment out the Sleep, the main thread exits before

    // the thread pool task runs. The thread pool uses background

    // threads, which do not keep the application running. (This

    // is a simple example of a race condition.)

    Thread.Sleep(1000);

    Console.WriteLine("Main thread exits.");

    }

    // This thread procedure performs the task.

    static void ThreadProc(Object stateInfo) {

    // No state object was passed to QueueUserWorkItem, so

    // stateInfo is null.

    Console.WriteLine("Hello from the thread pool.");}

    }

    &

    !&

    &

  • 7/27/2019 curs .NET 8-9.pdf

    11/30

    4F4' F&!!

    4'6#-"/ -F!!!

    &"$%

    '3

    )

    '301

    ".

    012"#

    "$%3"#7"%+777

    45'39=

    ".

    012"#

    "$%3"#7"%+77

    745

    '3#.

    012"#

    "$%3"#8%7"%+

    *+77%-7%%45

    &

    H'3H'-+""&-"/

    H"H.!H5'3E5

    [C#]

    using System;

    using System.Threading;

    // TaskInfo contains data that will be passed to the callback

    // method.

    public class TaskInfo {

  • 7/27/2019 curs .NET 8-9.pdf

    12/30

    public RegisteredWaitHandle Handle = null;

    public string OtherInfo = "default";

    }

    public class Example {

    public static void Main(string[] args)

    {

    // The main thread uses AutoResetEvent to signal the

    // registered wait handle, which executes the callback

    // method.

    AutoResetEvent ev = new AutoResetEvent(false);

    TaskInfo ti = new TaskInfo();

    ti.OtherInfo = "First task";

    // The TaskInfo for the task includes the registered wait

    // handle returned by RegisterWaitForSingleObject. This

    // allows the wait to be terminated when the object has

    // been signaled once (see WaitProc).

    ti.Handle = ThreadPool.RegisterWaitForSingleObject(

    ev,

    new WaitOrTimerCallback(WaitProc),

    ti,

    1000,

    false

    );

    // The main thread waits three seconds, to demonstrate the

    // time-outs on the queued thread, and then signals.

    Thread.Sleep(3100);

    Console.WriteLine("Main thread signals.");

    ev.Set();

    // The main thread sleeps, which should give the callback

    // method time to execute. If you comment out this line, the

    // program usually ends before the ThreadPool thread can

    execute.

    Thread.Sleep(1000);

    // If you start a thread yourself, you can wait for it to end

    // by calling Thread.Join.

    //This option is not available with thread pool threads.

    }

    // The callback method executes when the registered wait times out,

    // or when the WaitHandle (in this case AutoResetEvent) is signaled.

    // WaitProc unregisters the WaitHandle the first time the event is

    // signaled.

    public static void WaitProc(object state, bool timedOut)

    {

    // The state object must be cast to the correct type, because the

    // signature of the WaitOrTimerCallback delegate specifies type

  • 7/27/2019 curs .NET 8-9.pdf

    13/30

    // Object.

    TaskInfo ti = (TaskInfo) state;

    string cause = "TIMED OUT";

    if (!timedOut)

    {

    cause = "SIGNALED";

    // If the callback method executes because the WaitHandle is

    // signaled, stop future execution of the callback method

    // by unregistering the WaitHandle.

    if (ti.Handle != null)

    ti.Handle.Unregister(null);

    }

    Console.WriteLine("WaitProc( {0} ) executes on thread {1};

    cause = {2}.",

    ti.OtherInfo,

    Thread.CurrentThread.GetHashCode().ToString(),

    cause);

    }

    }

    "#!'.

    '6#-"/+#$-"/

    #$!

  • 7/27/2019 curs .NET 8-9.pdf

    14/30

    [JScript]

    public class AutoResetEvent extends WaitHandle

    IJ

    4 IJ "# )"#"!

    +""

    " ) ""

    #.

    HH''$

    "#"

    "!

    C2

  • 7/27/2019 curs .NET 8-9.pdf

    15/30

    #$!E

    ,,*&+5KC"$56-"#$*HL+5KKLD

    M

    M

    "-6H8E%HL+5KKLE

    %E

    "$CD"$$E

    ?H&E

    CDH&C"-6DE

    99-!! #E

    N)$%M

    )$+)$%EO

    ,,F!&!&!

    H>EP"-6EBB

    M%H+

    %LKKL#LLE

    ,,+&!"$$H&"$C:>>>>>>DE

    ?%

  • 7/27/2019 curs .NET 8-9.pdf

    16/30

    +'(L6&.LE

    O

    M,,!&

    +'(L&.LE

    OO

    O

    ,,'6#

    M

    "%E""$CD"$$E

    "E

    "#%"$CD"$$

    M!%H%E!"$$H"$$E!HE

    O

    O

    'M

    &+H>E'MO

    ,,

    ,, !H,,

    "$34M

    &%"H&+E&+E

    +'(L#&M>OL

    &%"#E,,

    ,, ,, "

    ,,#H#E

    6#'HE

    ,,+&!

    $M

    'H&6#%6+E

    ''"$$>"$$(!E

  • 7/27/2019 curs .NET 8-9.pdf

    17/30

    O

    $

    M'NHM

    '+E

    O

    ,,#!!&!!+'(L&M>OL

    &%"#E-!345

    O

    OO

    #!!

    ##!!

    #!% #!!-"/

    '-!"#-'!"!!!'3

    #

    [C#]

    using System;using System.Threading;

    class CalculateTest

    {

    static void Main()

    {

    Calculate calc = new Calculate();

    Console.WriteLine("Result = {0}.",

    calc.Result(234).ToString());

    Console.WriteLine("Result = {0}.",

    calc.Result(55).ToString());

    }

    }

    class Calculate

    {

    double baseNumber, firstTerm, secondTerm, thirdTerm;

    AutoResetEvent[] autoEvents;

    ManualResetEvent manualEvent;

    // Generate random numbers to simulate the actual calculations.

    Random randomGenerator;

  • 7/27/2019 curs .NET 8-9.pdf

    18/30

    public Calculate()

    {

    autoEvents = new AutoResetEvent[]

    {

    new AutoResetEvent(false),

    new AutoResetEvent(false),

    new AutoResetEvent(false)

    };

    manualEvent = new ManualResetEvent(false);

    }

    void CalculateBase(object stateInfo)

    {

    baseNumber = randomGenerator.NextDouble();

    // Signal that baseNumber is ready.

    manualEvent.Set();

    }

    // The following CalculateX methods all perform the same

    // series of steps as commented in CalculateFirstTerm.

    void CalculateFirstTerm(object stateInfo)

    {

    // Perform a precalculation.

    double preCalc = randomGenerator.NextDouble();

    // Wait for baseNumber to be calculated.

    manualEvent.WaitOne();

    // Calculate the first term from preCalc and baseNumber.

    firstTerm = preCalc * baseNumber *

    randomGenerator.NextDouble();

    // Signal that the calculation is finished.

    autoEvents[0].Set();

    }

    void CalculateSecondTerm(object stateInfo)

    {

    double preCalc = randomGenerator.NextDouble();

    manualEvent.WaitOne();

    secondTerm = preCalc * baseNumber *

    randomGenerator.NextDouble();

    autoEvents[1].Set();

    }

    void CalculateThirdTerm(object stateInfo)

    {

    double preCalc = randomGenerator.NextDouble();

    manualEvent.WaitOne();

    thirdTerm = preCalc * baseNumber *

    randomGenerator.NextDouble();

    autoEvents[2].Set();

    }

  • 7/27/2019 curs .NET 8-9.pdf

    19/30

    public double Result(int seed)

    {

    randomGenerator = new Random(seed);

    // Simultaneously calculate the terms.

    ThreadPool.QueueUserWorkItem(

    new WaitCallback(CalculateBase));

    ThreadPool.QueueUserWorkItem(

    new WaitCallback(CalculateFirstTerm));

    ThreadPool.QueueUserWorkItem(

    new WaitCallback(CalculateSecondTerm));

    ThreadPool.QueueUserWorkItem(

    new WaitCallback(CalculateThirdTerm));

    // Wait for all of the terms to be calculated.

    WaitHandle.WaitAll(autoEvents);

    // Reset the wait handle for the next calculation.

    manualEvent.Reset();

    return firstTerm + secondTerm + thirdTerm;

    }

    }

    6"

    #$-"/

    [Visual Basic]

    NotInheritable Public Class Monitor

    [C#]public sealed class Monitor

    [C++]

    public __gc __sealed class Monitor

    [JScript]

    public class Monitor

    +"""

  • 7/27/2019 curs .NET 8-9.pdf

    20/30

    - ".!"""

    " " 5

    #$ !#H"""!

    "H#"" ."!

    . 6 " #%!"

    "%H' " . !" "

    " " " 6 Q$R"""

    )"""""

    '.-':1"#H#""!

    !

    6 +A

    )

    " #$+#!"

    #$! -6"

  • 7/27/2019 curs .NET 8-9.pdf

    21/30

    C7#D

    "#

    &"

    '

    )

    "

    .""

    [C#]

    // This example shows how a Mutex is used to synchronize access

    // to a protected resource. Unlike Monitor, Mutex can be used with

    // WaitHandle.WaitAll and WaitAny, and can be passed across

    // AppDomain boundaries.

    using System;

    using System.Threading;

    class Test

    {

    // Create a new Mutex. The creating thread does not own the

    // Mutex.

    private static Mutex mut = new Mutex();

    private const int numIterations = 1;

    private const int numThreads = 3;

    static void Main()

    {

    // Create the threads that will use the protected resource.

    for(int i = 0; i < numThreads; i++)

    {

    Thread myThread = new Thread(

    new ThreadStart(MyThreadProc));

    myThread.Name = String.Format("Thread{0}", i + 1);

    myThread.Start();

    }

    // The main thread exits, but the application continues to

    // run until all foreground threads have exited.

    }

    private static void MyThreadProc()

    {

    for(int i = 0; i < numIterations; i++)

    {

    UseResource();

    }

  • 7/27/2019 curs .NET 8-9.pdf

    22/30

    }

    // This method represents a resource that must be synchronized

    // so that only one thread at a time can enter.

    private static void UseResource()

    {

    // Wait until it is safe to enter.

    mut.WaitOne();

    Console.WriteLine("{0} has entered the protected area",

    Thread.CurrentThread.Name);

    // Place code to access non-reentrant resources here.

    // Simulate some work.

    Thread.Sleep(500);

    Console.WriteLine("{0} is leaving the protected area\r\n",

    Thread.CurrentThread.Name);

    // Release the Mutex.mut.ReleaseMutex();

    }

    }

  • 7/27/2019 curs .NET 8-9.pdf

    23/30

    !# '01 /

    %!!&&'

    .6"!

    ++(S#+-%

    6+("

    ) "

    +#(+#

    +( #$

  • 7/27/2019 curs .NET 8-9.pdf

    24/30

    #%

    !*+

    ""5

    345

    #"#$

  • 7/27/2019 curs .NET 8-9.pdf

    25/30

    ,,!!

    ,,!)-(E

    "M

    ,,(!"/!E

    ,,!

    ,,!

    -(H)%&E

    ,,4!"/

    !EO

    ,,".$$

    ,,!!")(MM,,(!"/

    !E

    ,,#!!

    ,,$")H-(E

    ,,4!"/

    !E

    ,,!!$"

    EO

    OO

    -1+

    ,,"#!M

    ,,(!"/-"/H!E

    E

    $M,,!"/

    ,,4!"/

    O$M

  • 7/27/2019 curs .NET 8-9.pdf

    26/30

    E

    O

    ,,O

    ,,#

    "#!M,,(!"/

    +34 =

    ,,!"/

    ,,4!"/ >

    ,,

    O

    $?M,,!!

    ,,!

    )-(E

    "M+34

    =,,!

    ,,!-(H)%&E

    >O

    ,,".$$

    ,,!!

    ")(MM

    +34 =

    99!%!@5

    >O

    O

    O

    #$

  • 7/27/2019 curs .NET 8-9.pdf

    27/30

    /$+A

    M

    ,,!!,,!

    )-(E

    "M+3!344=

    ,,!

    ,,!

    -(H)%&EO

    O

    ,,".$$,,!!

    ")(M

    M+3!344=

    ,,!!-(E

    OO

    OO)"

    #

    #$E

    #$!E

    MM

    ,,+!"/

    H&E

    ,,!

    ,,!"/"!345

    ,,6@!

    ,,!"/":5

  • 7/27/2019 curs .NET 8-9.pdf

    28/30

    A345

    ,,6&6,,!!!.NA"$&$345

    ,,'!"&N+'(L(LE

    O

    ,,!!$@6!B34

    =

    99$7@C99$+

    99.%;8+799$+D

    +34 =

    99& > >O

    /

    $E8&%

    M

    ,,-"/

    ,,$$!

    %@+:8%345,,!!

    ,,!)-(E

    "M

    +3@+4=,,!

    ,,!-(H)%&EO

    O

    ,,".$$,,!!

    ")(M

    M

  • 7/27/2019 curs .NET 8-9.pdf

    29/30

    +3@+4=

    ,,!!

    -(EOO

    O

    O

    " "

    M,,-"/

    ,,$$!%@+:8%345

    ,,!!,,!)-(E

    "M+3@+4=,,!

    ,,!-(H)%&EO

    O

    ,,".$$

    ,,!!

    ")(MM+3@+4=

    ,,!!-(EO

    O

    OO

    #

    !$

  • 7/27/2019 curs .NET 8-9.pdf

    30/30

    M

    ,,"