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

转载于:https://www.cnblogs.com/guozhe/archive/2012/05/31/2528297.html

ASP.NET多线程编程(一) 收藏相关推荐

  1. ASP.NET温故而知新学习系列之ASP.NET多线程编程—.NET下的多线程编程应用程序域(七)...

    阅读目录 一:应用程序域概述 二:应用程序域和线程的关系 三:线程跨越多个应用程序域实例 四:运行效果 一:应用程序域 . 在.NET中有个特点,在.NET中有个CLR,在操作系统和我们编程环境之间有 ...

  2. ASP.NET温故而知新学习系列之ASP.NET多线程编程—异步编程(九)

    阅读目录 一:同步处理 二:异步处理 三:异步委托 四:通过委托同步调用方法 五:通过委托异步调用方法 一:同步处理 一个同步操作会阻塞整个当前的进程,直到这个操作完成才能执行下一段代码 二:异步处理 ...

  3. 多线程编程技术开发资料

    多线程编程技术开发资料 目录 Win32 多线程的性能(1)... 1 Win32 多线程的性能(2)... 10 关于多线程的一些细节... 23 用VC++5.0 实 现 多 线 程 的 调 度  ...

  4. 《C#多线程编程实战(原书第2版)》——第3章 使用线程池 3.1 简介

    本节书摘来自华章出版社<C#多线程编程实战(原书第2版)>一书中的第3章,第3.1节,作者(美)易格恩·阿格佛温(Eugene Agafonov),黄博文 黄辉兰 译,更多章节内容可以访问 ...

  5. .NET多线程编程入门

    在.NET多线程编程这个系列我们讲一起来探讨多线程编程的各个方面.首先我将在本篇文章的开始向大家介绍多线程的有关概念以及多线程编程的基础知识;在接下来的文章中,我将逐一讲述.NET平台上多线程编程的知 ...

  6. 一文看懂Python多进程与多线程编程(工作学习面试必读)

    进程(process)和线程(thread)是非常抽象的概念, 也是程序员必需掌握的核心知识.多进程和多线程编程对于代码的并发执行,提升代码效率和缩短运行时间至关重要.小编我今天就来尝试下用一文总结下 ...

  7. 对linux中多线程编程中pthread_join的理解

    对linux中多线程编程中pthread_join的理解 分类: 程序员面试 linux学习2013-08-04 21:32 234人阅读 评论(0) 收藏 举报 多线程linuxpthread_jo ...

  8. 《C#多线程编程实战》读书笔记

    本文是一篇读书笔记,由<C#多线程编程实战>一书中的内容整理而来,主要梳理了.NET中多线程编程相关的知识脉络,从Thread.ThreadPool.Task.async/await.并发 ...

  9. java多线程编程从入门到卓越(超详细总结)

    导读:java多线程编程不太熟?或是听说过?或是想复习一下?找不到好的文章?别担心我给你们又安利一波,文章内容很全,并且考虑到很多开发中遇到的问题和解决方案.循环渐进,通俗易懂,文章较长,建议收藏再看 ...

最新文章

  1. linux远程访问及控制
  2. Java try语句的嵌套
  3. eclipselink_EclipseLink JPA-RS简介
  4. MYSQL 5.7 INNODB 表空间
  5. 揭秘阿里百亿级云客服实时分析架构是怎么炼成的?
  6. Oracle冷备迁移过程和在线日志损坏处理
  7. xcode cocos2dx 3.x mac工程 当assert(cond)触发断点,但cond却为0
  8. 中国双频前端模块市场趋势报告、技术动态创新及市场预测
  9. Exchange2007使用POP3/SMTP协议收发邮件
  10. struts2从form取值的三种方式
  11. 在WINCE中的一些VB.NET2005通用方法
  12. 数据挖掘技术之关联分析
  13. Java语言程序设计(第3版)沈泽刚主编第6,7,8章课后习题答案
  14. html登录界面QQ微信图标,discuz修改QQ登录图标和微信登录图标的方法
  15. velocity参数重新赋值_Velocity 语法详解
  16. 虚拟机ubuntu与真实机实现实现复制粘贴、传输文件
  17. 2012年8月 至 2014年2月1日读书列表
  18. 大数据和人工智能概念全面解析
  19. Luat模块应用手册-示例-Luat DEMO-长连接超低功耗方案
  20. Java设计模式面试专题

热门文章

  1. [react] 说说react的生命周期有哪些?
  2. [react] 怎样将事件传递给子组件?
  3. 前端学习(3073):vue+element今日头条管理-删除文章失败(配合axios使用)
  4. 前端学习(2971):前一天回顾
  5. [html] webSocket怎么做兼容处理?
  6. 工作328:uni-局部过滤器处理数据
  7. [js] setTimeout的第三个参数有什么用?
  8. “睡服”面试官系列第二十一篇之class基本语法(建议收藏学习)
  9. 前端学习(1391):多人管理项目11邮箱地址查询信息
  10. shiro学习(24):Spring的transaction-manager的用法