locked
Thread.CurrentPrincipal.Identity getting changed when calling Async method in webapi function RRS feed

  • Question

  • Hi,

    I have a function in which I am calling an async method. Above all I am setting the thread identity to some custom identity. But identity is being changed after execution of async method. I used below method to execute Async function in webapi to solve the issue but suspect if it's really needed to do so.

    public async Task RunAsyncMethod(Func<Task> asyncOperation) 
            { 
                var currentContext = SynchronizationContext.Current;   

                SynchronizationContext.SetSynchronizationContext(new SynchronizationContext()); 

                await asyncOperation(); 

                SynchronizationContext.SetSynchronizationContext(currentContext); 
            }

    • Moved by CoolDadTx Friday, May 19, 2017 2:38 PM ASP.NET related
    Tuesday, May 16, 2017 1:00 PM

All replies

  • First of all the question why you need to set the SynchronizationContext to that one which was before calling the async method, the async and await keyword will take care of that and in the case of web application like web API you really don't need to do this, leave it to the framework to handle it itself.

    Hope it helps!


    [If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click Answered"Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]


    Blog | LinkedIn | Stack Overflow | Facebook
    profile for Ehsan Sajjad on Stack Exchange, a network of free, community-driven Q&A sites


    Tuesday, May 16, 2017 5:20 PM
  • Hi,

    Custom type value in Thread.CurrentPrincipal.Identity is being replaced by System.Security.Claims.ClaimsIdentity type if I don't use this code. I also want to avoid from this code. 
    I tried ConfigureAwait to keep the original synchronizationContext but it didn't work.
    Please suggest.


    Wednesday, May 17, 2017 10:55 AM
  • Please post questions related to Web API in the ASP.NET forums. They can better explain there why your context is getting changed and how you can solve this issue in web API correctly.
    Friday, May 19, 2017 2:38 PM