首页 > 代码库 > C#多线程并发精确控制例子
C#多线程并发精确控制例子
网上找了很久都找不到好点的例子,于是自己写了一个!
主要演示多线程,委托,回调
核心代码:
public partial class frmStart : Form { #pragma warning disable 0618 public delegate void AddCulumCallBack(int index,int i); public AddCulumCallBack addCulumCallBack; ManualResetEvent resumeEvent = new ManualResetEvent(false); public frmStart() { InitializeComponent(); addCulumCallBack = new AddCulumCallBack(AddCulum); } public void AddCulum(int index,int i) { this.lvShow.Items[index].SubItems[1].Text = "多线程并发运行测试:"+i.ToString(); } private void btnInitil_Click(object sender, EventArgs e) { for (int i = 0; i < 30; i++) { ListViewItem lvi = new ListViewItem(""); lvi.SubItems.Add(i.ToString()); this.lvShow.Items.Add(lvi); } } private string GetWebRequest(string url) { Uri uri = new Uri(url); WebRequest myReq = WebRequest.Create(uri); WebResponse result = myReq.GetResponse(); Stream receviceStream = result.GetResponseStream(); StreamReader readerOfStream = new StreamReader(receviceStream, System.Text.Encoding.GetEncoding("utf-8")); string strHTML = readerOfStream.ReadToEnd(); readerOfStream.Close(); receviceStream.Close(); result.Close(); return strHTML; } private void btnStart_Load(object sender, EventArgs e) { } List<Thread> listThread; private void button1_Click(object sender, EventArgs e) { listThread = new List<Thread>(); for (int i = 0; i < 30; i++) { object index = i; Thread myThread = new Thread(Method); myThread.Start(i); listThread.Add(myThread); } } public void Method(object index) { string a = GetWebRequest("http://www.baidu.com"); for (int i = 0; i < 10000; i++) { this.BeginInvoke(addCulumCallBack, index,i); Thread.Sleep(100); } } private void btnPauseThread_Click(object sender, EventArgs e) { foreach (Thread item in listThread) { item.Suspend(); } } private void btnGoAhead_Click(object sender, EventArgs e) { foreach (Thread item in listThread) { item.Resume(); } } private void btnClose_Click(object sender, EventArgs e) { foreach (Thread item in listThread) { item.Abort(); } listThread.Clear(); } }
C#多线程并发精确控制例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。