Access HttpContext.Current from different threads

前端 未结 5 2046
轻奢々
轻奢々 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:08

    In my application there are a lot of code that uses HttpContext.Current and I can not modify that code.

    worker.DoWork() from sample below uses that code. And I had to run it in separate thread.

    I came to the following solution:

     HttpContext ctx = HttpContext.Current;
     Thread t = new Thread(new ThreadStart(() =>
                    {
                        HttpContext.Current = ctx;
                        worker.DoWork();
                    }));
     t.Start();
     // [... do other job ...]
     t.Join();
    
    0 讨论(0)
  • 2020-11-27 03:08

    You can save it to the database and then, you can let the user's browser to keep refreshing or using ajax or using the new signalr to check if the result is already written in db. hope it helps.

    0 讨论(0)
  • 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! :)

    0 讨论(0)
  • 2020-11-27 03:18

    Just add the HttpContext.Current to the constructor of your class SiteCrawler.cs

    public class SiteCrawler
    {
         HttpContext context = HttpContext.Current;
    
        public void Method()
        {
            context.WhateverYouWant
        }
    }
    
    0 讨论(0)
  • 2020-11-27 03:21

    Have a look at this article by Fritz Onion: Use Threads and Build Asynchronous Handlers in Your Server-Side Web Code. It's quite long, but your requirement is not too trivial.

    Also K. Scott Allen posted a somewhat shorter article about this very issue: Working With HttpContext.Current

    0 讨论(0)
提交回复
热议问题