从不同线程访问 HttpContext.Current
我有一个 C# ASP.NET 应用程序,它启动大约 25 个不同的线程,运行名为 SiteCrawler.cs 的类中的一些方法。
在 HttpContext.Current.Session 中,我想保存用户搜索的结果,并在所有线程运行完毕后将其呈现给用户。我的问题是 HttpContext.Current
对象在生成的线程中为 null,因为它在那里不存在。
由于应用程序是多线程时的限制,我还有哪些其他选项可以在不使用会话的情况下保存用户/会话特定数据?
我试图在 Stackoverflow 的每一寸地方进行搜索以找到解决方案,但没有任何运气......
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
I 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.Current
object is null in the spawned threads because it doesn't exist there.
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....
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在我的应用程序中,有很多使用
HttpContext.Current
的代码,我无法修改这些代码。下面示例中的
worker.DoWork()
使用该代码。我必须在单独的线程中运行它。我得出以下解决方案:
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:
看看 Fritz Onion 写的这篇文章: 在服务器端 Web 代码中使用线程并构建异步处理程序。虽然很长,但您的要求并不是太微不足道。
K. Scott Allen 还针对这个问题发布了一篇较短的文章:使用 HttpContext.Current
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
@Rory 在上面做了评论,即使将
HttpContext
中的某些对象传递到线程中,它也会变为 null。我的User
属性就发生过这种情况。因此,您可以将 User 复制到线程 CurrentPrincipal,如下所示:在控制器上下文中,保存用户:
在线程中,设置“线程”用户:
请注意,HttpContext 仅在请求的生命周期内可用。该线程的生存时间可能比请求长得多,这可能就是您首先需要线程的原因! :)
@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 theUser
property. So instead you can copy the User to the thread CurrentPrincipal like this:In the controller context, save off the user:
In the thread, set the 'Thread's' 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.Current 添加到类 SiteCrawler.cs 的构造函数中
Just add the HttpContext.Current to the constructor of your class SiteCrawler.cs
您可以将其保存到数据库中,然后,您可以让用户的浏览器不断刷新或使用ajax或使用新的信号器来检查结果是否已写入数据库中。希望有帮助。
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.