C#(asp.net)多线程用法示例(可用于同时处理多个任务)

时间:2022-01-16 16:58:50

本文实例讲述了C#(asp.net)多线程用法。分享给大家供大家参考,具体如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Threading;
using System.Web.UI.WebControls;
public partial class muti_thread : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    Thread Thread1 = new Thread(new ThreadStart(CalcSum));
    Thread Thread2 = new Thread(new ThreadStart(CalcGap));
    Thread1.Start();
    Thread2.Start();
    Thread1.Join();
    Thread2.Join();
  }
  //求和方法
  protected void CalcSum()
  {
    long sum = 0;
    for (long i = 0; i < 100; i++)
    {
      sum += i;
      Response.Write(string.Format("Thread1-->i={0}:sum={1}<br/>", i, sum));
      Response.Flush();
      System.Threading.Thread.Sleep(5000);
    }
  }
  //求差方法
  protected void CalcGap()
  {
    long gap = 0;
    for (long i = 100; i >= 0; i--)
    {
      gap = i - 1;
      Response.Write(string.Format("Thread2-->i={0}:gap={1}<br/>", i, gap));
      Response.Flush();
      System.Threading.Thread.Sleep(1000);
    }
  }
}

希望本文所述对大家C#程序设计有所帮助。