c#中Thread的基本使用

下面再对此进行详细描述.

Thread类的构造函数有2类:

 一种是不带参数(ThreadStart 委托) --

 public Thread(ThreadStart start);



另一种是带参数(ParameterizedThreadStart 委托) --

public Thread(ParameterizedThreadStart start);

ParameterizedThreadStart 委托签名:

public delegate void ParameterizedThreadStart(Object obj);

示例:

1. 不带参数:

       // 定义线程方法:

        private static void ThreadMain()
        {
            Console.WriteLine("This is other thread main method.");
        }

    // 调用:

            Thread mythread = new Thread(ThreadMain);
            mythread.Start();

2. 带参数:

        // 定义线程方法:

        private static void MainThreadWithParameters(object o)
        {
            Data d = (Data)o;  //类型转换
            Console.WriteLine("Running in a thread, received {0}", d.Message);
        }

    public struct Data
    {
        public string Message;
    }

    // 调用:

            var data = new Data { Message = "Info" };
            Thread t2 = new Thread(MainThreadWithParameters);
            t2.Start(data);  // 传入参数

3. 通过定义类传递参数:

// 定义存放数据和线程方法的类:

    public class MyThread
    {
        private string message;
        public MyThread(string data)
        {
            this.message = data;
        }
        public void ThreadMethod()
        {
            Console.WriteLine("Running in a thread, data: {0}", this.message);  
        }
    }

// 调用

            var obj = new MyThread("info");
            Thread myThread = new Thread(obj.ThreadMethod); //ThreadStart 委托
            mythread.Start(); 


 .NET框架是C#的运行时类库,.NET是一个多线程的环境。线程(Thread)是进程中一个单一的顺序控制流程。线程是进程中的实体。一个进程可以有多个线程,一个线程必须有一个父进程。

     线程一般具有read,blocking和operation三种基本状态。由三种基本状态,衍化出五种线程的基本操作。首先,derive,线程是在进程内派生出来的。其次,schedule,选择一个ready的线程进入operation状态。第三,block,如果一个线程在执行过程中需要等待某个事件发生则被阻塞。第四,unblock,如果事件开始,则该线程被unblock,进入ready队列。第五,finish,线程结束,它执行过的寄存器上下文及堆栈内容会被释放。

     新线程是新产生的线程对象,它还没有分配资源。因此只能用start()或close()方法。

     Runable状态就是线程在start()方法运行后,得到线程所必需资源并且调用run()方法执行。

     Not Runable非运行状态是发生以下事件而进入的状态,suspend()方法被调用,sleep()方法被调用,线程使用wait()来等待条件变量,线程处于I/O等待。

    Dead是当Run()方法返回,或别的线程调用stop()方法,线程进入Dead状态。下边是Thread的两个简单例子。

 

复制代码
Using System;
using  System.Threading;
public class SimpleThread
{
     public void Method()
     {
          int i = 1,j = 2;
          int result = i + j ;
          Console.WriteLine("thread{0} Value{1}",
          AppDomain.GetCurrentThreadId().ToString,
          result.ToString());
     }  
     static void Main()
     {
          SimpleThread thread1 = new SimpleThread();
          thread1.Method();
          ThreadStart ts = new ThreadStart(thread1.Method);
          Thread t = new Thread(ts);
          t.Start();
          Console.ReadLine();
      }
}
复制代码

 

复制代码
 1 using System;
 2 using System.Threading;
 3 
 4 public class ThreadExample
 5 {
 6        public static void ThreadProc()
 7        {
 8               for(int i = 0; i <10; i++)
 9               {
10                   Console.WriteLine("ThreadProc:{0}",i);
11                   Thread.Sleep(0);
12               }
13         }
14         public static void Main()
15         {
16                Console.WriteLine("Main thread: Start a second thread.");
17                Thread t =new Thread(new ThreadStart(ThreadProc));
18                t.Start();
19                for(int i = 0; i < 4; i++)
20                {
21                     Console.WriteLine("Main thread:Do some work.");
22                     Thread.Sleep(0);
23                }
24                 Console.WriteLine("Main thread:Call Join(),to wait until ThreadProc ends.");
25                 t.Join();
26                 Console.WriteLine(Main thread:ThreadProc.Join has returned.Press Enter to end program.");
27                 Console.ReadLine();
28          }
29 } 
复制代码

  • 5
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#,Monitor类提供了一种同步机制,用于管理共享资源的并发访问。它可以用于实现互斥访问,即一次只允许一个线程访问共享资源。 要使用Monitor类,首先需要创建一个对象作为锁定对象。然后,可以使用Monitor类的静态方法来对该对象进行锁定和解锁操作。 下面是一个简单的示例,演示了如何使用Monitor来保护共享资源的访问: ```csharp class Program { static object lockObj = new object(); static int count = 0; static void Main(string[] args) { // 创建多个线程来访问共享资源 for (int i = 0; i < 5; i++) { Thread t = new Thread(IncrementCount); t.Start(); } Console.ReadLine(); } static void IncrementCount() { // 对lockObj进行锁定 Monitor.Enter(lockObj); try { // 访问共享资源 count++; Console.WriteLine("Count: " + count); } finally { // 解锁lockObj Monitor.Exit(lockObj); } } } ``` 在上面的示例,我们创建了一个共享资源count和一个锁定对象lockObj。在IncrementCount方法,我们使用Monitor.Enter方法对lockObj进行锁定,确保只有一个线程可以进入临界区。然后,在访问共享资源之后,我们使用Monitor.Exit方法解锁lockObj,以便其他线程可以继续进入临界区。 请注意,在使用Monitor时,应始终在try/finally块进行锁定和解锁操作,以确保即使在发生异常时也能正确释放锁定。 这只是Monitor类的基本用法示例,你可以根据具体需求进行更复杂的同步操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值