In my C# application, I use Impersonation
to extend access rights of users. For convenience, I just added a public static Impersonation
object, which is initialized at App startup.
The code for Impersonation
is from this answer on stackoverflow.
Executing any code in the app so far works fine:
someCodeThatNeedsImpersonation(); // Fine
somethingElse();
I now want to move code into a BackgroundWorker
:
BackgroundWorker bw = new BackgroundWorker();
bw.DoWork += (s, a) =>
{
someCodeThatNeedsImpersonation(); // fails to "see" impersonation
}
bw.RunWorkerCompleted += (s, a) =>
{
somethingElse();
}
bw.RunWorkerAsync();
This fails, because apparently the Impersonation
handle that was initialized in the main thread is not used in the BackgroundWorker
.
A quick fix, of course, is
bw.DoWork += (s, a) =>
{
using ( new Impersonation(...) )
{
someCodeThatNeedsImpersonation(); // works, because of bw's own impersonation
}
}
but I would prefer a solution that doesn't need a new Impersonation handle in every BackgroundWorker (because I will surely forget one). Is there a way to share the static Impersonation
object of the main thread?