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

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/422449.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

html如何查看文档,查看文档

设计步骤(返回正文)一、绘制表格1、在手动设计Html模板之前&#xff0c;我们先需要一个模板的样式&#xff0c;这个样式我们可以拿原来的纸质的样式&#xff0c;也可以在Excel表格中画一个样式&#xff0c;如图1所示&#xff0c;我们后面的设计都要根据这个表格来进行设计。图1…

父亲的忠告:把孩子培养成普通人

现在你用不到&#xff0c;将来你肯定用的到。你一定会做个好爸爸。 转自&#xff1a;http://luo.bo/25512/转载于:https://www.cnblogs.com/webcc/archive/2012/06/01/2531207.html

U盘装XP系统(含截图,2012最新原创超简单方法)

U盘装XP系统(含截图&#xff0c;2012最新原创超简单方法)首先准备好3样必备东西 1.U盘2.XP系统&#xff08;推荐GhostXP SP3 2012统一论坛最新版&#xff1b;迅雷快传下载地址&#xff1a;http://kuai.xunlei.com/d/BMLHLZHXVGKT&#xff09;3.制作U盘WINPE软件(推荐UltraISO&a…

2021年峰峰春晖中学高考成绩查询,峰峰春晖中学2019年录取分数线

技校网专门为您推荐的类似问题答案问题1&#xff1a;河北丰润车轴山中学2011年录取分数线按学校名次录取问题2&#xff1a;广州美术中学2011年中考录取分数线提前批优先线为693分&#xff0c;比往年略高。公费线640分&#xff0c;择校、民办线为620分。问题3&#xff1a;2009年…

推到重做

自己做到太差了&#xff0c;完全是在1.16的基础上进行了少量的修改&#xff0c;和自己当初的想法完全不一样&#xff0c;推到重新做&#xff01;&#xff01;&#xff01; 先找下思路&#xff0c;复习下自己的系统以及uboot烧写过程。 自带Uboot烧写过程 硬件检测结果&#xff…

广东省2021年普通高考成绩复查结果查询,广东省2021年普通高考英语听说考试成绩可以查询啦!...

广东省2021年普通高考英语听说考试评卷工作已经结束。现将考试成绩发布的有关事项通知如下。一、考试成绩发布广东省2021年普通高考英语听说考试成绩将于4月28日统一发布。高考英语听说考试成绩按考生卷面成绩(满分60分)3&#xff0c;四舍五入取整数后计得。英语听说考试成绩与…

c#完美截断字符串(中文+非中文)

public static string Truncation(this HtmlHelper htmlHelper, string str, int len){if (str null || str.Length 0 || len < 0){return string.Empty;}int l str.Length;#region 计算长度int clen 0;while (clen < len && clen < l){//每遇到一个中文&…

2021辽宁大洼高中高考成绩查询,2021大洼高中最后一跑——励志高考,逆袭人生...

六月的天&#xff0c;湛蓝六月的风&#xff0c;不燥六月的日子&#xff0c;激情四溢六月里的故事&#xff0c;总是以青春为主题六月里的大洼高中高三学子们迎来了人生重要的里程碑——高考2021年6月5日&#xff0c;是大洼高中高三学子们热情饱满准备出征高考、逆袭人生的日子。…

jQuery ajax 和 普通js ajax 笔记

首先引用 两个js 文件 1 <script src"js/jquery-1.7.1.js" type"text/javascript"></script> 2 <script src"js/Common.js" type"text/javascript"></script> html 代码&#xff1a; 1 <body> 2 …

html 在手机上运行,怎么在手机上打开HTML

回答&#xff1a;一1、我们打开XMind软件2、点击插入----超链接3、我们输入我们的网址二使用二&#xff1a;XMind如何分享&#xff0c;XMind提供非常强大的共享功能&#xff0c;而且在不断完善&#xff0c;那么大家知道XMind如何分享吗&#xff1f;其实操作还是简单的。1、我们…

attribute 扩展

今天参考json-c的源码 读到一个关于attribute 扩展 static void json_object_init(void) __attribute__ ((constructor)); static void json_object_fini(void) __attribute__ ((destructor)); google到含义如下 void main_enter() __attribute__((constructor));//main_enter函…

计算机等级的有关知识,计算机等级二级基础知识.doc

计算机等级二级基础知识认真复习&#xff0c;努力冲刺&#xff0c;成功通过&#xff01;计算机基础知识教材张福炎孙志挥主编的南京大学出版社《大学计算机信息技术教程》。考题都是以单项选择题形式出现命题的基本考虑以常识性、实用性知识为主以知识点为单元进行考核基础部分…

background 旋转_基于HTML5 Canvas实现工控2D叶轮旋转

之前在拓扑上的应用都是些静态的图元&#xff0c;今天我们将在拓扑上设计一个会动的图元——叶轮旋转。我们先来看下这个叶轮模型长什么样从模型上看&#xff0c;这个叶轮模型有三个叶片&#xff0c;每一个叶片都是不规则图形&#xff0c;显然无法用上我们HT for Web的基础图形…

linux命令 scp

man scp: scp copies files between hosts on a network. 最简单的用法:scp zzr10.103.33.131:/var/log/zzrlog /var/www/zzr/The authenticity of host 10.103.33.131 (10.103.33.131) cant be established.RSA key fingerprint is 8b:c3:5e:a0:cf:0d:69:bd:xx:xx:xx:xx:xx:xx…

link引入html5,CSS引入方式 | link和@import的区别 — 生僻的前端考点

link和import的区别HTML5学堂&#xff1a;CSS的引入方式有外部引入、页面头部书写、标签内联书写&#xff0c;其实还有import的引入方式&#xff0c;但是现在基本被淘汰掉了。为了让大家了解到更多的知识&#xff0c;今天给大家分享link和import的区别。页面中使用CSS的方式主要…

h5活动是什么意思_深度|场景赋能H5,365天让保险线上拓客更广更容易

上周局长和大家分析了保险头部公司母亲节的一些“新玩法“&#xff08;戳这里可回看&#xff09;&#xff0c;不难看出&#xff0c;在当下这种特殊的环境中&#xff0c;保险公司都在打通线上线下双运营模式&#xff0c;都在寻求更多不一样的拓客机遇。在普华永道的最新研究报告…

数据量化算法

数据量化算法 数据量化算法 1. 四舍五入 float val 0.9; int nval val 0.5;2. 浮点类型的数组int quantization(float * pnote, int note_num, int * out_template){float best_shift -1000.0f;float min_dist 10000.0f; //最小路径 //寻找最小路径(最佳偏移值…