ASP.NET多線程編程(一) 收藏

來源:互聯網
上載者:User
 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>");
   }
  } 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.