首页 > 代码库 > C# 多线程并发
C# 多线程并发
public partial class MultiThread : Form { public int threadh;//线程代号 public string strUrl;//接收文件的URL public FileStream fs; public HttpWebRequest request; public byte[] nbytes;//接收缓冲区 public int nreadsize;//接收字节数 int conts; int Conted; public MultiThread() { //不对错误线程进行调用 System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; InitializeComponent(); } //ThreadStart start private void butquantity_Click(object sender, EventArgs e) { if (txtquantity.Text != "") { conts = Convert.ToInt32(txtquantity.Text); Thread[] threads = new Thread[conts]; for (int i = 0; i < conts; i++) { threads[i] = new Thread(new ThreadStart(ReadHttp)); threads[i].Name = i.ToString() + "线程号"; } foreach (Thread t in threads) { t.Start(); //textBox2.Text = Thread.CurrentThread.Name; } InitializeTimer(); } else { MessageBox.Show("请求数量不能为空!", "ERROR"); } } private void timerClock_Elapsed(object source, ElapsedEventArgs e) { if (txtquantity.Text != "") { conts = Convert.ToInt32(txtquantity.Text); Thread[] threads = new Thread[conts]; for (int i = 0; i < conts; i++) { threads[i] = new Thread(new ThreadStart(ReadHttp)); threads[i].Name = i.ToString() + "线程号"; } foreach (Thread t in threads) { t.Start(); } } else { MessageBox.Show("请求数量不能为空!", "ERROR"); } } //发送请求 private void ReadHttp() { try { Conted = Convert.ToInt32(txtquantity.Text); System.Net.WebClient client = new System.Net.WebClient(); strUrl = txtAddress.Text; //this.textBox2.Text = "正在请求" + strUrl; Stream st = client.OpenRead(strUrl); StreamReader sr = new StreamReader(st); string res = sr.ReadToEnd(); if (res != null) { listBox1.Items.Add("-->" + Thread.CurrentThread.Name + "成功"); } else { listBox1.Items.Add("-->" + Thread.CurrentThread.Name + "失败"); } sr.Close(); st.Close(); Thread.Sleep(2000); } catch (Exception e) { MessageBox.Show(e.Message, "提示:"); //throw; } } public void InitializeTimer() { System.Timers.Timer timerClock = new System.Timers.Timer(); timerClock.Elapsed += new ElapsedEventHandler(timerClock_Elapsed); //timerClock.Interval = 1000 * 60 * 3; timerClock.Interval = 3000; timerClock.Enabled = true; } }}
C# 多线程并发
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。