[.NET] - Thread and impersonate feature

I lost a large amount of time to understand what going on with my threads when they're trying to write inside an FTP. It failed everytime in QA and PROD...
The reason was due to impersonate feature used for QA and PROD to precise to the program the 'execution user' (rather than application pool by default for a web app).

Unfortunately, if you are trying to create new threads inside your main app which are using now your impersonate defined user: they will not use it! And they will take the default 'execution user'...

So the rule -> always think to force your new threads to use the impersonate user by giving it through arguments

Please find the way of doing it with Task.Run

public void Main(){  
   var impersonateUser = System.Security.Principal.WindowsIdentity.GetCurrent();
   Task.Run(() => MyAsyncMethod(impersonateUser));

public void MyAsyncMethod(){  
   WindowsImpersonationContext impersonateContext = null;
   if (windowsIdentityToUse != null)
   impersonateContext = windowsIdentityToUse.Impersonate();


   if (impersonateContext != null)

Of course, for other kind of thread initialization you always have a method to inject parameters, so don't be afraid ;) Let me know if you need another particular example ;)

P.S.: if you want to get or log the current user used to execute your program, of course you can use as well: System.Security.Principal.WindowsIdentity.GetCurrent()