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>");
   }
  }
 

posted on 2012-05-31 13:25  水行者  阅读(333)  评论(0编辑  收藏  举报

导航