-1

Let´s say I have a class like this:

class Test{

   private string status;

   public Test(){

      //Do some processing. After processing is done assign

    status = "processdone_uniqueidhere";

      }    
}

Now, in my asp.net application I need to periodically check status using a timer for a value when the processing is done.

Basically, I can store the reference of the class "Test" in session such as:

Test t = new Test();
Session["uniquesession"] = (Test)t;

This was, in the timer, I can retrieve the instance of the class from the session and check for the value of status:

Test t = (Test)Session["uniquesession"];

string value = t.status;

I´m not able to store the reference in a ViewState even if I declare the class as [Serializable]. Not sure why. Works with session though.

The other method is to declare the class as static and declare the variable status as static and public and check the value like this:

string value = Test.status;

Which way is most stable and which way is bad practice?

4

2 回答 2

0

如果这是特定于当前用户的,请使用 Session。

如果它是全局的,请使用 Cache 或静态成员。

于 2013-07-18T21:10:51.150 回答
0

你以错误的方式解决这个问题。如果需要共享它应该是静态的,并且不应该存储在会话中。会话用于维护每个用户的状态的易失性信息,而不是用于在用户之间共享的东西。更重要的是,如果你移动到进程外会话,你的类将被定期序列化和反序列化,这可能会重置或弄乱你的计时器。更不用说会话何时到期,课程就消失了。

让它成为静态的,但更重要的是,仔细思考课程的目标是什么,以及它为什么需要存在。将瞬态的、易失的数据放在 Session 中,而不是带有逻辑的类。

于 2013-07-18T21:11:48.560 回答