During web development, we can use httpcontext. Current. items to share resources of a single process throughout its lifecycle.
For example, use a conection for each Web Request (the advantage of this is that you do not open or close the database every time, it can improve performance, and you can close it through httpmodule)
In the development of CSProgramHttpcontext. current. items will report an error. I have the honor to solve this problem when I recently developed a framework. (Of course, the solution is based on the framework.Code).
Using System;
Using System. Collections. Generic;
Using System. text;
Using System. Threading;
Using System. Security. permissions;
Using System. runtime. remoting. messaging;
Using System. runtime. interopservices;
Using System. collections;
Namespace Fox. Tools. threadtool
{
[Serializable, comvisible ( True ), Securitypermission (securityaction. linkdemand, flags = Securitypermissionflag. Infrastructure)]
Public Class Threadresourse
{
Private Idictionary _ items;
Public Idictionary items
{
Get
{
If ( This . _ Items = Null )
{
This . _ Items = New Hashtable ();
}
Return This . _ Items;
}
}
Public Static Threadresourse current
{
Get
{
Return (Contextbase. Current As Threadresourse );
}
Set
{
Contextbase. Current = Value;
}
}
Internal Class Contextbase
{
// Methods
Internal Static Object Switchcontext ( Object Newcontext)
{
Object Hostcontext = Callcontext. hostcontext;
If (Hostcontext ! = Newcontext)
{
Callcontext. hostcontext = Newcontext;
}
Return Hostcontext;
}
// Properties
Internal Static Object Current
{
Get
{
If ( Null = Callcontext. hostcontext)
{
Callcontext. hostcontext = New Threadresourse ();
}
Return Callcontext. hostcontext;
}
[Securitypermission (securityaction. Demand, unrestricted = True )]
Set
{
Callcontext. hostcontext = Value;
}
}
}
}
}
The test code is as follows: Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using Nunit. Framework;
Using Fox. Tools. threadtool;
Namespace Testlibrary
{
[Testfixture]
Public Class Class4
{
[Test]
Public Void Testjiagou ()
{
// CATEGORY me = basicdal <Category>. GetObject (5 );
Threadresourse. Current. Items. Add ( " Key " , " Value " );
String SS = Threadresourse. Current. items [ " Key " ] As String ;
}
}
}
The results were achieved on schedule.
In the underlying framework of development, I design it like this.
Public Partial Class Globalinfo
{
Public Static Idictionary items
{
Get
{
If (Globalinfo. iswebsite) // Httpcontext. Current. items is returned for website development.
{
Return Httpcontext. Current. items;
}
Else
{
Return Threadresourse. Current. items;
}
}
}
}
In this way, you only need to call globalinfo. items to read and write the content.