C# 从不同线程访问 HttpContext.Current

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8925227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:12:56  来源:igfitidea点击:

Access HttpContext.Current from different threads

c#asp.netsessionhttpcontext

提问by Raydk

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

我有一个 C# ASP.NET 应用程序,它启动大约 25 个不同的线程,在名为 SiteCrawler.cs 的类中运行一些方法。

In HttpContext.Current.SessionI want to save the result of the search made by the user and present it to the user when all the threads are finished running. My problem is that the HttpContext.Currentobject is null in the spawned threads because it doesn't exist there.

HttpContext.Current.Session我想保存用户搜索的结果,并在所有线程运行完毕后将其呈现给用户。我的问题是该HttpContext.Current对象在生成的线程中为空,因为它不存在于那里。

What other options do I have to save user/session specific data without using session because of the limitations when the application is multithreaded?

由于应用程序是多线程时的限制,我还有哪些其他选项可以在不使用会话的情况下保存用户/会话特定数据?

I have tried to search around every inch of Stackoverflow to find a solution but without any luck....

我试图搜索 Stackoverflow 的每一寸以找到解决方案,但没有任何运气......

回答by ysrb

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.

您可以将其保存到数据库中,然后您可以让用户的浏览器保持刷新或使用ajax或使用新的信号器检查结果是否已写入db。希望能帮助到你。

回答by Dennis Traub

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.

看看 Fritz Onion 的这篇文章:在服务器端 Web 代码中使用线程和构建异步处理程序。它很长,但你的要求不是太简单。

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

另外 K. Scott Allen 发表了一篇关于这个问题的较短的文章:使用 HttpContext.Current

回答by Dmitry Andrievsky

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

在我的应用程序中有很多使用的代码,HttpContext.Current我无法修改这些代码。

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

worker.DoWork()从下面的示例使用该代码。我不得不在单独的线程中运行它。

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();

回答by jjspierx

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

只需将 HttpContext.Current 添加到您的类 SiteCrawler.cs 的构造函数中

public class SiteCrawler
{
     HttpContext context = HttpContext.Current;

    public void Method()
    {
        context.WhateverYouWant
    }
}

回答by Jess

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

@Rory 在上面发表了评论,HttpContext即使您将其传递到线程中,其中的某些对象也会变为空。这发生在我身上User。因此,您可以将 User 复制到线程 CurrentPrincipal 中,如下所示:

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! :)

请注意, HttpContext 仅在请求的生命周期内可用。该线程可能会比请求存活的时间长得多,这可能是您首先需要一个线程的原因!:)