Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / MS Press - Msdn Training Programming Net Framework With C#

.pdf
Скачиваний:
174
Добавлен:
12.02.2016
Размер:
16.87 Mб
Скачать

Module 14 (Optional): Threading and Asynchronous Programming

3

 

 

 

Overview of Threads

Topic Objective

To define threads in the context of general multitasking and state the primary advantages and disadvantages of using threads.

Lead-in

Whether you are developing for computers with one processor or several, you want your application to provide the most responsive interaction with the user, even if the application is currently doing other work.

!Threads

#The basic unit to which an operating system allocates processor time

#Enable multiple activities to appear to occur simultaneously

!Advantages of using multiple threads

#Application does background processing while keeping the UI responsive

#Distinguish tasks of varying priority

#Communicate over a network, to a Web server, and to a database

!Potential disadvantages of using threads

#Diminished performance due to increased operating system overhead, for example, thread context switching

#Controlling code execution with many threads is complex, and can be a source of many difficult to find and fix bugs

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Whether you are developing for computers with one processor or several, you want your application to provide the most responsive interaction with the user, even if the application is currently doing other work. Using multiple threads of execution is one of the most powerful ways to keep your application responsive to the user and at the same time make use of the processor in between or even during user events.

Delivery Tip

You can quickly illustrate how multiple threads are used to create nonblocking UI by running the Microsoft Internet Explorer Web browser. Start the browser and type a URL address or click a link to a site that takes some time to download. Show how you can still interact with the application during this download operation, for example, canceling the current download by clicking

Stop.

Threads

Threads are the basic unit to which an operating system allocates processor time, and more than one thread can execute code inside a process. Each thread maintains exception handlers, a scheduling priority, and a set of structures that the system uses to save the thread context until it is scheduled. The thread context includes all of the information that the thread needs to smoothly resume execution, including the thread’s set of CPU registers and stack, in the address space of the thread’s host process.

Operating systems use processes to separate the different applications that they are executing. The .NET Framework further subdivides an operating system process into lightweight, managed subprocesses, called application domains, represented by System.AppDomain. One or more managed threads, represented by System.Threading.Thread, can run in one or any number of application domains within the same process. A preemptive multitasking operating system allocates a processor time slice to each thread that it executes. Because each time slice is small, multiple threads appear to execute at the same time.

4Module 14 (Optional): Threading and Asynchronous Programming

Advantages of using multiple threads

Threads enable multiple activities to appear to occur simultaneously in an application. For example, a user can edit a worksheet while another thread recalculates other parts of the worksheet within the same application. Threading maintains the responsiveness of the user interface while background processing is occurring. Threads can be used to enable users to receive notification of a task’s progress, and even to cancel the task at any time.

You can also use threads to distinguish tasks of varying priority. For example, you can use a high-priority thread to manage time-critical tasks, and a lowpriority thread to perform other tasks.

Threads are also useful when an application must wait for an event, such as user input or a read from the network or from a file, before continuing to execute. Multiple threads enable the processor to handle a separate task while waiting for the completion of the event.

Potential disadvantages of using threads

In some circumstances, threading may cause application performance to degrade. On a single-processor computer, a compute-bound task, such as calculating a series of values by using multiple threads, would be slower because of the overhead caused by thread-switching. Keeping track of a large number of threads consumes significant processor time. If there are too many threads, most of them will not make significant progress.

Controlling code execution with many threads is complex, and can be a source of many bugs. You run the risk of data corruption or other problems, such as deadlocks and race conditions. To protect an application’s data from possible corruption, you must ensure that access to shared data is properly synchronized.

For more information about deadlocks and race conditions, see Thread Safety in this module.

Note While this module focuses on threading, there are other ways of achieving concurrency that include using multiple processes/AppDomains, messaging, and database stored procedures.

Module 14 (Optional): Threading and Asynchronous Programming

5

 

 

 

Overview of Support for Threading in .NET

Topic Objective

To provide a high-level overview of the

System.Threading namespace and introduce the asynchronous design pattern.

Lead-in

Before examining how threads work in the .NET Framework, let’s briefly review important ways in which the .NET Framework provides support for threading.

!Basic thread namespace

#System.Threading

!Standard design pattern for asynchronous programming

#Hides thread creation and synchronization details

#Supported by .NET Framework delegate classes and/or the IAsyncResult interface

*****************************ILLEGAL FOR NON-TRAINER USE******************************

To provide support for multithreaded programming, the .NET Framework supplies its own namespace for thread creation and management and a programming model to handle asynchronous operations.

Basic thread namespace

The System.Threading namespace provides classes and interfaces that enable multithreaded programming. System.Threading includes classes that are used to create and manage threads, protect shared data, and improve system responsiveness.

The System.Threading.Thread class is an abstraction of a managed thread that executes within the runtime. This includes threads that are created by the runtime and those that are created outside the runtime but that interact with the runtime environment to execute some managed code.

The System.Threading namespace includes classes that assist with thread synchronization and protection of shared data. For example, the System.Threading.Interlocked class provides atomic operations for variables that are shared by multiple threads. The System.Threading.Monitor class provides a synchronization mechanism to ensure that where multiple threads access a shared resource, only one thread can access the resource at a particular time.

6Module 14 (Optional): Threading and Asynchronous Programming

Standard design pattern for asynchronous programming

The standard asynchronous design pattern in the .NET Framework provides an efficient model to manage asynchronous operations and provide a consistent programming model. The .NET Framework provides support for asynchronous programming using the IAsyncResult interface and delegate classes that enable a programmer to avoid some of the implementation details of threading. The asynchronous design pattern is covered in more detail later in this module.

For more information about the System.Threading namespace and its classes, see System.Threading Namespace in the .NET Framework SDK documentation.

Module 14 (Optional): Threading and Asynchronous Programming

7

 

 

 

Thread Architecture in .NET

Topic Objective

To explain thread architecture in .NET in terms of application domains.

Lead-in

Let’s look at the different architectural components that make up a single .NET process.

Example of a Process Hosting AppDomains

AppDomain A

AppDomain B

Shared Data

 

Shared Data

Shared Data

 

Shared Data

Thread 1

Thread 2

Thread 3

Thread

Thread

Thread

Thread

Thread

Thread

Specific

Specific

Specific

Specific

Specific

Specific

Data

Data

Data

Data

Data

Data

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Application domains, also known as AppDomains, play a key role in how threads work in the .NET Framework. An application domain is a runtime representation of a logical process within a physical process. A single process can contain multiple application domains, each of which is completely isolated from other application domains within this or any other process. One or more threads run in an application domain.

Although hosting threads within application domains is conceptually similar to the COM threading model with its use of apartments, there is an important difference: application domains are managed types whereas the COM threading model is built on an unmanaged architecture.

For more information about application domains, see Module 2, “Introduction to a Managed Execution Environment,” in Course 2349B, Programming with the Microsoft .NET Framework (Microsoft Visual C# .NET).

8Module 14 (Optional): Threading and Asynchronous Programming

Mapping from Win32 Threading to Managed Threading

The following table maps Microsoft Win32® threading elements to their approximate runtime equivalent. Note that this mapping does not represent identical functionality. For example, TerminateThread does not execute finally clauses or free up resources, and cannot be prevented. However, Thread.Abort executes all of your rollback code, reclaims all of the resources, and can be denied by using ResetAbort. Be sure to read the .NET Framework SDK closely before making assumptions about functionality.

In Win32

In the common language runtime

CreateThread

Combination of new Thread() and

 

Thread.Start

TerminateThread

Thread.Abort

SuspendThread

Thread.Suspend

ResumeThread

Thread.Resume

Sleep

Thread.Sleep

WaitForSingleObject on the thread handle

Thread.Join

ExitThread

No equivalent

GetCurrentThread

Thread.CurrentThread

SetThreadPriority

Thread.Priority

No equivalent

Thread.Name

No equivalent

Thread.IsBackground

Close to CoInitializeEx (Ole32.dll)

Thread.ApartmentState

Module 14 (Optional): Threading and Asynchronous Programming

9

 

 

 

" Using Threads in .NET

Topic Objective

To provide an overview of the topics that you will cover in this section.

Lead-in

Having briefly reviewed how an operating system uses threads to perform multitasking, let’s look at how threading works in the

.NET Framework.

!Starting Threads

!Thread Properties and Parameters

!Managing Threads

!Thread Local Storage

!Interrupting and Terminating Threads

*****************************ILLEGAL FOR NON-TRAINER USE******************************

In this section you will learn how to start, manage, and terminate threads.

The System.Threading namespace includes classes for starting managing, and terminating threads.

Being able to perform basic threading operations is only the first requirement in creating multithreaded applications. On a more advanced level, you must consider issues of data protection and performance. These issues are covered in the topic Thread Safety in this module.

10

Module 14 (Optional): Threading and Asynchronous Programming

Starting Threads

Topic Objective

To explain how to instantiate and start a new thread by using the .NET Framework classes.

Lead-in

Creating a new instance of a Thread class creates a new managed thread.

!Create a new instance of a Thread Object

#Constructor takes a ThreadStart delegate as its only parameter

#ThreadStart references the method that will be executed by the new thread

!Thread is not executed until the Thread.Start method is invoked

Thread t = new

Thread t = new

Thread(new ThreadStart(MyClass.AStaticMethod));

Thread(new ThreadStart(MyClass.AStaticMethod));

t.Start();

t.Start();

*****************************ILLEGAL FOR NON-TRAINER USE******************************

Creating a new instance of a Thread class creates a new managed thread. The constructor for Thread takes, as its only parameter, a ThreadStart delegate that references the method that will be executed by the new thread. The Thread function does not begin executing until the Start method is called.

Module 14 (Optional): Threading and Asynchronous Programming

11

 

 

 

The following code shows how to create and start new threads:

using System;

using System.Threading;

class MyClass

{

//…

public static void AStaticMethod()

{

//…

}

public void AnInstanceMethod()

{

//…

}

}

class App

{

static void Main()

{

//Create and start thread on an instance method MyClass aMyClass = new MyClass();

Thread t1 = new

Thread(new ThreadStart(aMyClass.AnInstanceMethod)); t1.Start();

//Create and start thread on a static method

Thread t2 = new

Thread(new ThreadStart(MyClass.AStaticMethod)); t2.Start();

//…

}

}

In the preceding example, the calls to t1.Start and t2.Start place the t1 and t2 threads in the running state, and the operating system can schedule them for execution. The Start method submits an asynchronous request to the system, and the call returns immediately, possibly before the new thread has started.

The thread’s execution begins at the first line of the method that is referred to by the thread delegate. Calling Start more than once on the same thread causes the runtime to throw a ThreadStateException.

12

Module 14 (Optional): Threading and Asynchronous Programming

Thread Properties and Parameters

Topic Objective

To describe some key Thread class properties and how to pass parameters to threads.

Lead-in

To get or set the name of a thread and its priority, use the Thread.Name and Thread.Priority properties.

!Use the Thread.Name and Thread.Priority properties to get or set the name and priority of the thread

!Designate a thread as a background or a foreground thread by setting the Thread.IsBackground property

#A background thread will not keep the managed execution environment alive

t.Name = "My Background Thread"; t.Name = "My Background Thread";

t.Priority = ThreadPriority.AboveNormal; t.Priority = ThreadPriority.AboveNormal; t.IsBackground = true;

t.IsBackground = true;

! Encapsulate thread parameters in an object

*****************************ILLEGAL FOR NON-TRAINER USE******************************

To get or set the name of a thread and its priority, use the Thread.Name and Thread.Priority properties. Thread.Priority gets or sets the following values that indicate the scheduling priority of a thread:

!Highest

!AboveNormal

!Normal

!BelowNormal

!Lowest

For example, to set the name of a thread t to “My Background Thread” and make its priority AboveNormal, you use the following code:

t.Name = "My Background Thread"; t.Priority = ThreadPriority.AboveNormal;

Note Because the details of scheduling algorithms vary with each operating system, operating systems are not required to honor the priority of a thread.

Соседние файлы в папке c#