Windows 模拟和 TPL
Windows Impersonation and TPL
我正在使用 WindowsIdentity.Impersonate
来读取远程注册表。但是,读取位于 Task
委托中的注册表的实际代码,因此它可能 运行 在不同的线程上。我的问题是在 UI 线程中模拟并在线程池中执行提升的工作是否合法?
更新:
// get userHandle from LogonUser(...)
Task task = Task.Run(() =>
{
using (impersonationContext = WindowsIdentity.Impersonate(userHandle))
{
// Do stuff here
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
}
因为您使用了 .NET Framework 4.0 中提供的 TPL。 WindowsIdentity
应该自动流动,除非您明确抑制流动。
In the .NET Framework versions 1.0 and 1.1, the WindowsIdentity
does not flow across any user-defined asynchronous points. In the .NET Framework version 2.0, there is an ExecutionContext
object that contains information about the currently executing thread, and flows it across asynchronous points within an application domain. The WindowsIdentity
also flows as part of the information that flows across the asynchronous points, which means that if an impersonation context exits it will flow as well. Source
我正在使用 WindowsIdentity.Impersonate
来读取远程注册表。但是,读取位于 Task
委托中的注册表的实际代码,因此它可能 运行 在不同的线程上。我的问题是在 UI 线程中模拟并在线程池中执行提升的工作是否合法?
更新:
// get userHandle from LogonUser(...)
Task task = Task.Run(() =>
{
using (impersonationContext = WindowsIdentity.Impersonate(userHandle))
{
// Do stuff here
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
}
因为您使用了 .NET Framework 4.0 中提供的 TPL。 WindowsIdentity
应该自动流动,除非您明确抑制流动。
In the .NET Framework versions 1.0 and 1.1, the
WindowsIdentity
does not flow across any user-defined asynchronous points. In the .NET Framework version 2.0, there is anExecutionContext
object that contains information about the currently executing thread, and flows it across asynchronous points within an application domain. TheWindowsIdentity
also flows as part of the information that flows across the asynchronous points, which means that if an impersonation context exits it will flow as well. Source