Thread usage
Using system;
Using system. Threading;
Public class threadexample
{
Public static void threadproc ()
{
For (INT I = 0; I <10; I ++)
{
Console. writeline ("threadproc: {0}", I );
Thread. Sleep (0 );
}
}
Public static void main ()
{
Console. writeline ("enable a thread in the main process ");
Thread t = new thread (New threadstart (threadproc); // create a thread
T. Start (); // start the thread
Thread Ts = new thread (New threadstart (threadproc); // create a thread
TS. Start (); // start the thread
TS. Suspend (); // suspends this thread
For (INT I = 0; I <4; I ++)
{
Console. WriteLine ("main process output ...... ");
Thread. Sleep (0); // The number of milliseconds the Thread is blocked. 0 indicates that this thread should be suspended so that other waiting threads can execute
}
Console. WriteLine ("the main thread calls the thread Join method until the ThreadProc1 thread ends .");
T. Join (); // block the calling thread until the end of a thread.
Console. WriteLine ("ThreadProc1 thread ended ");
Ts. Resume ();
// Ts. IsBackground = true; // run in the background
}
} Parameter passing in Thread
Using System;
Using System. Threading;
Namespace ThreadArgs
{
Public class SimpleThread
{
Private string procParameter = "";
Public SimpleThread (string strPara)
{
ProcParameter = strPara;
}
Public void WorkerMethod ()
{
Console. WriteLine ("parameter input:" + procParameter );
}
}
Class MainClass
{
Static void Main (string [] args)
{
SimpleThread st = new SimpleThread ("this is a parameter string! ");
Thread t = new Thread (new ThreadStart (st. WorkerMethod ));
T. Start ();
T. Join (Timeout. Infinite );}
}
} Use of delegation in Thread
Using System;
Using System. Threading;
Public class SimpleThread
{
Public delegate void Start (object o );
Private class Args
{
Public object o;
Public Start s;
Public void work ()
{
S (o );
}
}
Public static Thread CreateThread (Start s, Object arg)
{
Args a = new Args ();
A. o = arg;
A. s = s;
Thread t = new Thread (new ThreadStart (a. work ));
Return t;
}
}
Class Worker
{
Public static void WorkerMethod (object o)
{
Console. WriteLine ("parameter:" + o );
}
}
Public class Work
{
Public static void Main ()
{
Thread t = SimpleThread. CreateThread (new SimpleThread. Start (Worker. WorkerMethod), "parameter string ");
T. Start ();
T. Join (Timeout. Infinite );
}
} The thread spans multiple program Domains
Using System;
Namespace AppDomainAndThread
{
Class Class1
{
Static void Main (string [] args)
{
AppDomain DomainA;
DomainA = AppDomain. CreateDomain ("MyDomainA ");
String StringA = "DomainA Value ";
DomainA. SetData ("DomainKey", StringA );
CommonCallBack ();
CrossAppDomainDelegate delegateA = new CrossAppDomainDelegate (CommonCallBack );
// CrossAppDomainDelegate delegate: DoCallBack is used for cross-application domain calls.
DomainA. DoCallBack (delegateA); // execute code in another application domain
}
Public static void CommonCallBack ()
{
AppDomain Domain;
Domain = AppDomain. CurrentDomain;
Console. WriteLine ("The value'" + Domain. GetData ("DomainKey") + "'was found
In "+ Domain. FriendlyName. ToString () +" running on thread
Id: "+ AppDomain. GetCurrentThreadId (). ToString ());
}
}
} Using System;
Using System. Threading;
Using System. Collections;
Namespace ClassMain
{Delegate string MyMethodDelegate ();
Class MyClass
{
Private static ArrayList arrList = new ArrayList ();
Private Static int I = 0;
Public static void add ()
{
Arrlist. Add (I. tostring ());
I ++;
}
Public static void lockadd ()
{
Lock (arrlist)
{
Add ();
}
}
Public static void interlickedadd ()
{
Interlocked. increment (Ref I );
Arrlist. Add (I. tostring ());
}
Public static void monitorlock ()
{
Try
{
// I. Unlimited time
// Monitor. Enter (arrList );
// II. Obtain the exclusive lock at the specified time
If (Monitor. TryEnter (arrList, TimeSpan. FromSeconds (30 )))
// Obtain the exclusive lock of an object within 30 seconds.
{
Add ();
}
}
Catch
{
// Custom error handling code when an exception occurs
}
Finally
{
Monitor. Exit (arrList); // The object must be released whether it is normal or an error occurs.
}
}
Static Thread [] threads = new Thread [10];
[STAThread]
Static void Main (string [] args)
{
For (int I = 0; I <3; I ++)
{
Thread thread = new Thread (new ThreadStart (Add ));
// Thread thread1 = new Thread (new ThreadStart (LockAdd ));
// Thread thread = new Thread (new ThreadStart (InterlickedAdd ));
// Thread thread = new Thread (new ThreadStart (MonitorLock ));
Thread. Start ();
}
Console. ReadLine ();
For (int I = 0; I <arrList. Count; I ++)
{
Console. WriteLine (arrList [I]. ToString ());
}
}
}
} Call the method asynchronously through delegation
Using System;
Using System. Threading;
Using System. Runtime. Remoting. Messaging;
Namespace ClassMain
{
// Delegate Declaration (function signature)
Delegate string MyMethodDelegate ();
Class MyClass
{
// Dynamic method to be called
Public string MyMethod1 ()
{
Return "Hello Word1 ";
}
// Static method to be called
Public static string MyMethod2 ()
{
Return "Hello word2 ";
}
}
Class class1
{
Static void main (string [] ARGs)
{
Myclass = new myclass ();
// Method 1: declare the delegate and call mymethod1
Mymethoddelegate d = new mymethoddelegate (myclass. mymethod1 );
String strend = D ();
Console. writeline (strend );
// Method 2: declare the delegate and call mymethod2 (using the asyncresult object)
D = new mymethoddelegate (myclass. mymethod2); // defines a delegate that can be used by multiple methods
Asyncresult myresult; // the result of the asynchronous call of this type of closed asynchronous delegation is obtained through asyncresult.
Myresult = (asyncresult) D. begininvoke (null, null); // start to call
While (! Myresult. iscompleted) // determines whether the thread execution is complete.
{
Console. writeline ("Asynchronous execution of mymethod2 .....");
}
Console. writeline ("method mymethod2 execution completed! ");
Strend = D. endinvoke (myresult); // wait until the method called by the delegate is completed and return the result
Console. writeline (strend );
Console. Read ();
}
}
} Use multithreading to implement the Web progress bar private void btndownload_click (Object sender, system. eventargs E)
{
System. Threading. Thread thread = new system. Threading. Thread (new system. Threading. threadstart (longtask ));
Thread. Start ();
Session ["State"] = 1;
OpenProgressBar (this. Page );
}
Public static void OpenProgressBar (System. Web. UI. Page)
{
StringBuilder sbScript = new StringBuilder ();
SbScript. Append ("<script language = 'javascript 'Type = 'text/JavaScript '> \ n ");
SbScript. Append ("<! -- \ N ");
// IE5.5 or above is required
// SbScript. Append ("window. showModalDialog ('ss ss. aspx ','', 'dialogheight:
100px; dialogWidth: 350px; edge: Raised; center: Yes; help: No;
Resizable: No; status: No; scroll: No; '); \ n ");
SbScript. Append ("window. open ('ss ss. aspx ','', 'height = 100, width = 350,
Toolbar = No, menubar = No, scrollbars = No, resizable = No, location = No,
Status = no'); \ n ");
Sbscript. append ("// --> \ n ");
Sbscript. append ("</SCRIPT> \ n ");
Page. registerclientscriptblock ("openprogressbar", sbscript. tostring ());
}
Private void longtask ()
{
// Simulate a long task
// Each Cyclic Simulation Task goes to different stages
For (INT I = 0; I <11; I ++)
{
System. Threading. thread. Sleep (1000 );
// Set the state value of each stage to display the current progress.
Session ["state"] = I + 1;
}
// Task ended
Session [& quot; State & quot;] = 100;
} Private int state = 0;
Private void page_load (Object sender, system. eventargs E)
{
// Put user code to initialize the page here
If (session ["state"]! = NULL)
{
State = convert. toint32 (session ["state"]. tostring ());
}
Else
{
Session ["state"] = 0;
}
If (State> 0 & State <= 10)
{
This. lblmessages. Text = "task undertaking! ";
This. panelprogress. width = State * 30;
This. lblpercent. Text = State * 10 + "% ";
Page. RegisterStartupScript ("", "<script> window. setTimeout ('window. Progress. submit () ', 100); </script> ");
}
If (state = 100)
{
This. panelProgress. Visible = false;
This. panelBarSide. Visible = false;
This. lblMessages. Text = "Task Completed! ";
Page. RegisterStartupScript ("", "<script> window. close (); </script> ");
}
}