线程

来源:互联网 发布:年代四部曲 知乎 编辑:程序博客网 时间:2024/06/05 14:07

The lock and SyncLock Keywords

The lock (C#) and SyncLock (Visual Basic) statements can be used to ensure that a block of code runs to completion without interruption by other threads.This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.

A lock or SyncLock statement is given an object as an argument, and is followed by a code block that is to be executed by only one thread at a time.For example:

C#
VB
public class TestThreading{    private System.Object lockThis = new System.Object();    public void Process()    {        lock (lockThis)        {            // Access thread-sensitive resources.        }    }}

The argument provided to the lock keyword must be an object based on a reference type, and is used to define the scope of the lock.In the example above, the lock scope is limited to this function because no references to the object lockThis exist outside the function.If such a reference did exist, lock scope would extend to that object.Strictly speaking, the object provided is used solely to uniquely identify the resource being shared among multiple threads, so it can be an arbitrary class instance.In practice, however, this object usually represents the resource for which thread synchronization is necessary.For example, if a container object is to be used by multiple threads, then the container can be passed to lock, and the synchronized code block following the lock would access the container.As long as other threads locks on the same contain before accessing it, then access to the object is safely synchronized.

Generally, it is best to avoid locking on a public type, or on object instances beyond the control of your application.For example,lock(this) can be problematic if the instance can be accessed publicly, because code beyond your control may lock on the object as well.This could create deadlock situations where two or more threads wait for the release of the same object.Locking on a public data type, as opposed to an object, can cause problems for the same reason.Locking on literal strings is especially risky because literal strings are interned by the common language runtime (CLR).This means that there is one instance of any given string literal for the entire program, the exact same object represents the literal in all running application domains, on all threads.As a result, a lock placed on a string with the same contents anywhere in the application process locks all instances of that string in the application.As a result, it is best to lock a private or protected member that is not interned.Some classes provide members specifically for locking.TheArray type, for example, provides SyncRoot.Many collection types provide aSyncRoot member as well.

For more information about the lock andSyncLock statements, see the following topics:

  • “锁定”语句(C# 参考)

  • SyncLock 语句

  • 监视器

Monitors

Like the lock and SyncLock keywords, monitors prevent blocks of code from simultaneous execution by multiple threads.TheEnter method allows one and only one thread to proceed into the following statements; all other threads are blocked until the executing thread callsExit.This is just like using the lock keyword.For example:

C#
VB
lock (x){    DoSomething();}

This is equivalent to:

C#
VB
System.Object obj = (System.Object)x;System.Threading.Monitor.Enter(obj);try{    DoSomething();}finally{    System.Threading.Monitor.Exit(obj);}

Using the lock (C#) or SyncLock (Visual Basic) keyword is generally preferred over using the Monitor class directly, both because lock or SyncLock is more concise, and becauselock or SyncLock insures that the underlying monitor is released, even if the protected code throws an exception.This is accomplished with thefinally keyword, which executes its associated code block regardless of whether an exception is thrown.

Synchronization Events and Wait Handles

Using a lock or monitor is useful for preventing the simultaneous execution of thread-sensitive blocks of code, but these constructs do not allow one thread to communicate an event to another.This requires synchronization events, which are objects that have one of two states, signaled and un-signaled, that can be used to activate and suspend threads.Threads can be suspended by being made to wait on a synchronization event that is unsignaled, and can be activated by changing the event state to signaled.If a thread attempts to wait on an event that is already signaled, then the thread continues to execute without delay.

There are two kinds of synchronization events:AutoResetEvent, and ManualResetEvent.They differ only in thatAutoResetEvent changes from signaled to unsignaled automatically any time it activates a thread.Conversely, aManualResetEvent allows any number of threads to be activated by its signaled state, and will only revert to an unsignaled state when itsReset method is called.

Threads can be made to wait on events by calling one of the wait methods, such asWaitOne, WaitAny, or WaitAll.WaitHandle.WaitOne causes the thread to wait until a single event becomes signaled,WaitHandle.WaitAny blocks a thread until one or more indicated events become signaled, andWaitHandle.WaitAll blocks the thread until all of the indicated events become signaled.An event becomes signaled when itsSet method is called.

In the following example, a thread is created and started by theMain function.The new thread waits on an event using theWaitOne method.The thread is suspended until the event becomes signaled by the primary thread that is executing theMain function.Once the event becomes signaled, the auxiliary thread returns.In this case, because the event is only used for one thread activation, either the AutoResetEvent or ManualResetEvent classes could be used.

C#
VB
using System;using System.Threading;class ThreadingExample{    static AutoResetEvent autoEvent;    static void DoWork()    {        Console.WriteLine("   worker thread started, now waiting on event...");        autoEvent.WaitOne();        Console.WriteLine("   worker thread reactivated, now exiting...");    }    static void Main()    {        autoEvent = new AutoResetEvent(false);        Console.WriteLine("main thread starting worker thread...");        Thread t = new Thread(DoWork);        t.Start();        Console.WriteLine("main thread sleeping for 1 second...");        Thread.Sleep(1000);        Console.WriteLine("main thread signaling worker thread...");        autoEvent.Set();    }}

Mutex Object

A mutex is similar to a monitor; it prevents the simultaneous execution of a block of code by more than one thread at a time.In fact, the name "mutex" is a shortened form of the term "mutually exclusive." Unlike monitors, however, a mutex can be used to synchronize threads across processes.A mutex is represented by theMutex class.

When used for inter-process synchronization, a mutex is called anamed mutex because it is to be used in another application, and therefore it cannot be shared by means of a global or static variable.It must be given a name so that both applications can access the same mutex object.

Although a mutex can be used for intra-process thread synchronization, usingMonitor is generally preferred, because monitors were designed specifically for the .NET Framework and therefore make better use of resources.In contrast, theMutex class is a wrapper to a Win32 construct.While it is more powerful than a monitor, a mutex requires interop transitions that are more computationally expensive than those required by theMonitor class.For an example of using a mutex, seeMutexes.

Interlocked Class

You can use the methods of the Interlocked class to prevent problems that can occur when multiple threads attempt to simultaneously update or compare the same value.The methods of this class let you safely increment, decrement, exchange, and compare values from any thread.

ReaderWriter Locks

In some cases, you may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated.TheReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows non-exclusive access when reading the resource.ReaderWriter locks are a useful alternative to exclusive locks, which cause other threads to wait, even when those threads do not need to update data.

Deadlocks

Thread synchronization is invaluable in multithreaded applications, but there is always the danger of creating adeadlock, where multiple threads are waiting for each other and the application comes to a halt.A deadlock is analogous to a situation in which cars are stopped at a four-way stop and each person is waiting for the other to go.Avoiding deadlocks is important; the key is careful planning.You can often predict deadlock situations by diagramming multithreaded applications before you start coding.

Related Sections

如何:使用线程池(C# 和 Visual Basic)

HOW TO: Synchronize Access to a Shared Resource in a Multithreading Environment by Using Visual C# .NET

HOW TO: Create a Thread by Using Visual C# .NET

HOW TO: Submit a Work Item to the Thread Pool by Using Visual C# .NET

HOW TO: Synchronize Access to a Shared Resource in a Multithreading Environment by Using Visual C# .NET

0 0