0

I have a problem when accessing httpcontext.current value at application_start method.
There is a lots of discussions about this topic.
But I want to share my business logic and I need some advice how to handle problem.

Let's look at this business logic together step by step

1-I want to design "custom object" which has "static global List" property and any user can add "LogObj" object to this list whereever actions occured.

public class MyLog
{
public static void List<LogObj> LogObjList {get;set;}
static MyLog()
{
LogObjList = new List<LogObj>();
}
}

2- If I have a "System.Timers.Timer" object which checks the "static global List" every X milliseconds and performs some action which defined in the code

public static init(){
System.Timers.Timer t = new System.Timers.Timer();
t.Elapsed += T_Elapsed;
t.Interval = 3000;
t.Start();
}

private void T_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//perform some code. 
var s = HttpContext.Current.Session["test"];
var logObj = MyLog.LogObjList[0] + s;
//save as text file ...
}

3- If I start init() method in application_start event at global.asax I get this error "object reference ..." where the line of "..HttpContext.Current.Session" started.

So
If I do not want to access any httpcontext.current's properties I have no problem at this situation.
But If I need to access any properties of httpcontext.current at Timer_Elapsed event I have problem about it.
So I need your advice or alternative way to making my algorithm.
Thank you

mrkiyak
  • 99
  • 1
  • 11
  • HttpContext.Current will only be available if your executing thread is part of Request Response processing. For more details please take a look at http://stackoverflow.com/questions/19509672/why-is-httpcontext-current-null. In your case you are using a background thread which has no awareness of HttpContext and that's why HttpContext.Current is null. Instead of using HttpContext, you can play with MemoryCache. It will be available everywhere. You can find more details about MemoryCache here https://msdn.microsoft.com/en-us/library/system.runtime.caching.memorycache(v=vs.110).aspx – Vinod Nov 22 '16 at 21:05
  • thank you Vinod for comment. I understand. I will try to use MemoryCache. Well what do you think about background thread in my business logic. Is that suitable for using when need doing something like that situations – mrkiyak Nov 22 '16 at 21:14

0 Answers0