从不同线程访问 HttpContext.Current [英] Access HttpContext.Current from different threads

查看:43
本文介绍了从不同线程访问 HttpContext.Current的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

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

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

推荐答案

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

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

worker.DoWork() 使用该代码.我不得不在单独的线程中运行它.

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

这篇关于从不同线程访问 HttpContext.Current的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆