共用方式為


Thread.BeginThreadAffinity 方法

定義

通知主機 Managed 程式碼即將執行指令,而這些指令相依於目前實體作業系統執行緒的識別 (Identity)。

public:
 static void BeginThreadAffinity();
public static void BeginThreadAffinity ();
[System.Security.SecurityCritical]
public static void BeginThreadAffinity ();
static member BeginThreadAffinity : unit -> unit
[<System.Security.SecurityCritical>]
static member BeginThreadAffinity : unit -> unit
Public Shared Sub BeginThreadAffinity ()
屬性

例外狀況

呼叫端沒有必要的權限。

範例

下列範例示範如何使用 BeginThreadAffinityEndThreadAffinity 方法來通知主機程式碼區塊相依于實體作業系統執行緒的身分識別。

using namespace System::Threading;
using namespace System::Security::Permissions;

public ref class MyUtility
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand, ControlThread=true)]
   void PerformTask()
   {
      // Code that does not have thread affinity goes here.
      //
      Thread::BeginThreadAffinity();
      //
      // Code that has thread affinity goes here.
      //
      Thread::EndThreadAffinity();
      //
      // More code that does not have thread affinity.
   }
};
using System.Threading;

public class MyUtility
{
    public void PerformTask()
    {
        // Code that does not have thread affinity goes here.
        //
        Thread.BeginThreadAffinity();
        //
        // Code that has thread affinity goes here.
        //
        Thread.EndThreadAffinity();
        //
        // More code that does not have thread affinity.
    }
}
open System.Threading

let performTask () =
    // Code that does not have thread affinity goes here.
    //
    Thread.BeginThreadAffinity()
    //
    // Code that has thread affinity goes here.
    //
    Thread.EndThreadAffinity()
    //
    // More code that does not have thread affinity.
Imports System.Threading
Imports System.Security.Permissions

<SecurityPermission(SecurityAction.Demand, Flags:=SecurityPermissionFlag.ControlThread)> _
Friend Class MyUtility
    <SecurityPermission(SecurityAction.Demand, Flags:=SecurityPermissionFlag.ControlThread)> _
    Public Sub PerformTask() 
        ' Code that does not have thread affinity goes here.
        '
        Thread.BeginThreadAffinity()
        '
        ' Code that has thread affinity goes here.
        '
        Thread.EndThreadAffinity()
        '
        ' More code that does not have thread affinity.
    End Sub
End Class

備註

Common Language Runtime 的某些主機,例如 Microsoft SQL Server 2005,會提供自己的執行緒管理。 提供自己執行緒管理的主機可以隨時將執行中工作從一個實體作業系統執行緒移至另一個執行緒。 大部分的工作都不會受到此切換的影響。 不過,有些工作具有線程親和性,也就是說,它們相依于實體作業系統執行緒的身分識別。 這些工作必須在執行不應切換的程式碼時通知主機。

例如,如果您的應用程式呼叫系統 API 來取得具有線程親和性的作業系統鎖定,例如 Win32 CRITICAL_SECTION,您必須先呼叫 BeginThreadAffinity ,才能取得鎖定,以及 EndThreadAffinity 釋放鎖定之後。

在SQL Server 2005 下執行的程式碼中使用這個方法,需要以最高主機保護層級執行程式碼。

適用於

另請參閱