Access HttpContext.Current from different threads

前端 未结 5 2068
轻奢々
轻奢々 2020-11-27 02:23

I have a C# ASP.NET application which starts about 25 different threads running some methods in a class called SiteCrawler.cs.

In HttpContext.Current.Session<

5条回答
  •  余生分开走
    2020-11-27 03:13

    @Rory made a comment above, that certain objects in the HttpContext will become null even if you pass it into the Thread. This happened to me with the User property. So instead you can copy the User to the thread CurrentPrincipal like this:

    In the controller context, save off the user:

                _user = HttpContext.Current.User;
                var processThread = new Thread(() => ThreadedCode());
                processThread.Start();
    

    In the thread, set the 'Thread's' user:

        private static void ThreadedCode()
        {
            // Workaround for HttpContext.Current.User being null.
            // Needed for CreatedBy and RevisedBy.
            Thread.CurrentPrincipal = _user;
    

    Note that the HttpContext will only be available for the lifetime of the request. The thread will live on potentially much longer than the request, which is probably why you need a thread in the first place! :)

提交回复
热议问题