ASP.NET多线程编程(一) 收藏
生活随笔
收集整理的這篇文章主要介紹了
ASP.NET多线程编程(一) 收藏
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Thread的使用
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("在主進程中啟動一個線程");
? Thread t = new Thread(new ThreadStart(ThreadProc));//創建一個線程
? t.Start();//啟動線程
? Thread ts = new Thread(new ThreadStart(ThreadProc));//創建一個線程
? ts.Start();//啟動線程
? ts.Suspend();//掛起該線程
? for (int i = 0; i < 4; i++)
? {
?? Console.WriteLine("主進程輸出……");
?? Thread.Sleep(0);//線程被阻塞的毫秒數。0表示應掛起此線程以使其他等待線程能夠執行
? }
? Console.WriteLine("主線程調用線程Join 方法直到ThreadProc1線程結束.");
? t.Join();//阻塞調用線程,直到某個線程終止時為止。
? Console.WriteLine("ThreadProc1線程結束");
? ts.Resume();
? //ts.IsBackground = true;//后臺運行
?}
} 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 ("參數輸入為: " + procParameter);
? }
?}
?class MainClass
?{
? static void Main(string[] args)
? {
?? SimpleThread st = new SimpleThread("這是參數字符串!");
?? Thread t? = new Thread( new ThreadStart( st.WorkerMethod ) );
?? t.Start ();
?? t.Join (Timeout.Infinite);? }
?}
} 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 ("參數為: " + o);
?}
}
public class Work
{
?public static void Main()
?{
? Thread t = SimpleThread.CreateThread (new SimpleThread.Start(Worker.WorkerMethod), "參數字符串");
? t.Start ();
? t.Join (Timeout.Infinite);
?}
} 線程跨越多個程序域
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委托:由 DoCallBack 用于跨應用程序域調用。
?? DomainA.DoCallBack(delegateA); //在另一個應用程序域中執行代碼
? }
? 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.不限時間
??? //Monitor.Enter(arrList);?
??? //II.在指定時間獲得排他鎖
??? if(Monitor.TryEnter(arrList,TimeSpan.FromSeconds(30)))
???? //在30秒內獲取對象排他鎖.
??? {??????????????????????????????????????????????????????????????????????
????? Add();
??? }
?? }
?? catch
?? {
??? //發生異常后自定義錯誤處理代碼
?? }
?? finally
?? {
??? Monitor.Exit(arrList);? //不管是正常還是發生錯誤,都得釋放對象
?? }
? }
? 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());
?? }
? }
?}
} 通過委托異步調用方法
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace?? ClassMain
{
?//委托聲明(函數簽名)
?delegate string MyMethodDelegate();
?class MyClass
?{
? //要調用的動態方法
? public? string MyMethod1()
? {
?? return "Hello Word1";
? }
? //要調用的靜態方法
? public static string MyMethod2()
? {
?? return "Hello Word2";
? }
?}
?class Class1
?{
? static void Main(string[] args)
? {
?? MyClass myClass = new MyClass();
?? //方式1:? 聲明委托,調用MyMethod1
?? MyMethodDelegate d = new MyMethodDelegate(myClass.MyMethod1);
?? string strEnd = d();??
?? Console.WriteLine(strEnd);
?? //方式2:? 聲明委托,調用MyMethod2 (使用AsyncResult對象調用)
?? d = new MyMethodDelegate(MyClass.MyMethod2); //定義一個委托可以供多個方法使用?????
?? AsyncResult myResult;?? //此類封閉異步委托異步調用的結果,通過AsyncResult得到結果.
?? myResult = (AsyncResult)d.BeginInvoke(null,null);??????? //開始調用
?? while(!myResult.IsCompleted)? //判斷線程是否執行完成
?? {
??? Console.WriteLine("正在異步執行MyMethod2 .....");
?? }
?? Console.WriteLine("方法MyMethod2執行完成!");
?? strEnd = d.EndInvoke(myResult);????? //等待委托調用的方法完成,并返回結果?
?? Console.WriteLine(strEnd);
?? Console.Read();
? }
?}
} 利用多線程實現Web進度條 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 Page)
? {
?? StringBuilder sbScript = new StringBuilder();
?? sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
?? sbScript.Append("<!--\n");
?? //需要IE5.5以上支持
?? //sbScript.Append("window.showModalDialog('Progress.aspx','','dialogHeight: 100px; dialogWidth: 350px; edge: Raised; center: Yes; help: No; resizable: No; status: No;scroll:No;');\n");
?? sbScript.Append("window.open('Progress.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()
? {
?? //模擬長時間任務
?? //每個循環模擬任務進行到不同的階段
?? for(int i=0;i<11;i++)
?? {
??? System.Threading.Thread.Sleep(1000);
??? //設置每個階段的state值,用來顯示當前的進度
??? Session["State"] = i+1;
?? }
?? //任務結束
?? Session["State"] = 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>");
?? }
? }
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("在主進程中啟動一個線程");
? Thread t = new Thread(new ThreadStart(ThreadProc));//創建一個線程
? t.Start();//啟動線程
? Thread ts = new Thread(new ThreadStart(ThreadProc));//創建一個線程
? ts.Start();//啟動線程
? ts.Suspend();//掛起該線程
? for (int i = 0; i < 4; i++)
? {
?? Console.WriteLine("主進程輸出……");
?? Thread.Sleep(0);//線程被阻塞的毫秒數。0表示應掛起此線程以使其他等待線程能夠執行
? }
? Console.WriteLine("主線程調用線程Join 方法直到ThreadProc1線程結束.");
? t.Join();//阻塞調用線程,直到某個線程終止時為止。
? Console.WriteLine("ThreadProc1線程結束");
? ts.Resume();
? //ts.IsBackground = true;//后臺運行
?}
} 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 ("參數輸入為: " + procParameter);
? }
?}
?class MainClass
?{
? static void Main(string[] args)
? {
?? SimpleThread st = new SimpleThread("這是參數字符串!");
?? Thread t? = new Thread( new ThreadStart( st.WorkerMethod ) );
?? t.Start ();
?? t.Join (Timeout.Infinite);? }
?}
} 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 ("參數為: " + o);
?}
}
public class Work
{
?public static void Main()
?{
? Thread t = SimpleThread.CreateThread (new SimpleThread.Start(Worker.WorkerMethod), "參數字符串");
? t.Start ();
? t.Join (Timeout.Infinite);
?}
} 線程跨越多個程序域
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委托:由 DoCallBack 用于跨應用程序域調用。
?? DomainA.DoCallBack(delegateA); //在另一個應用程序域中執行代碼
? }
? 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.不限時間
??? //Monitor.Enter(arrList);?
??? //II.在指定時間獲得排他鎖
??? if(Monitor.TryEnter(arrList,TimeSpan.FromSeconds(30)))
???? //在30秒內獲取對象排他鎖.
??? {??????????????????????????????????????????????????????????????????????
????? Add();
??? }
?? }
?? catch
?? {
??? //發生異常后自定義錯誤處理代碼
?? }
?? finally
?? {
??? Monitor.Exit(arrList);? //不管是正常還是發生錯誤,都得釋放對象
?? }
? }
? 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());
?? }
? }
?}
} 通過委托異步調用方法
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
namespace?? ClassMain
{
?//委托聲明(函數簽名)
?delegate string MyMethodDelegate();
?class MyClass
?{
? //要調用的動態方法
? public? string MyMethod1()
? {
?? return "Hello Word1";
? }
? //要調用的靜態方法
? public static string MyMethod2()
? {
?? return "Hello Word2";
? }
?}
?class Class1
?{
? static void Main(string[] args)
? {
?? MyClass myClass = new MyClass();
?? //方式1:? 聲明委托,調用MyMethod1
?? MyMethodDelegate d = new MyMethodDelegate(myClass.MyMethod1);
?? string strEnd = d();??
?? Console.WriteLine(strEnd);
?? //方式2:? 聲明委托,調用MyMethod2 (使用AsyncResult對象調用)
?? d = new MyMethodDelegate(MyClass.MyMethod2); //定義一個委托可以供多個方法使用?????
?? AsyncResult myResult;?? //此類封閉異步委托異步調用的結果,通過AsyncResult得到結果.
?? myResult = (AsyncResult)d.BeginInvoke(null,null);??????? //開始調用
?? while(!myResult.IsCompleted)? //判斷線程是否執行完成
?? {
??? Console.WriteLine("正在異步執行MyMethod2 .....");
?? }
?? Console.WriteLine("方法MyMethod2執行完成!");
?? strEnd = d.EndInvoke(myResult);????? //等待委托調用的方法完成,并返回結果?
?? Console.WriteLine(strEnd);
?? Console.Read();
? }
?}
} 利用多線程實現Web進度條 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 Page)
? {
?? StringBuilder sbScript = new StringBuilder();
?? sbScript.Append("<script language='JavaScript' type='text/javascript'>\n");
?? sbScript.Append("<!--\n");
?? //需要IE5.5以上支持
?? //sbScript.Append("window.showModalDialog('Progress.aspx','','dialogHeight: 100px; dialogWidth: 350px; edge: Raised; center: Yes; help: No; resizable: No; status: No;scroll:No;');\n");
?? sbScript.Append("window.open('Progress.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()
? {
?? //模擬長時間任務
?? //每個循環模擬任務進行到不同的階段
?? for(int i=0;i<11;i++)
?? {
??? System.Threading.Thread.Sleep(1000);
??? //設置每個階段的state值,用來顯示當前的進度
??? Session["State"] = i+1;
?? }
?? //任務結束
?? Session["State"] = 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>");
?? }
? }
轉載于:https://www.cnblogs.com/guozhe/archive/2012/05/31/2528297.html
總結
以上是生活随笔為你收集整理的ASP.NET多线程编程(一) 收藏的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos镜像 from_【CentO
- 下一篇: Java垃圾回收机制详解(万字总结!一篇