C# 并行编程指南之Thread

使用C# 原始的多线程技术,即Thread技术

使用Thread类首先要引入 System.Threading命名空间

Thread类有两个常用构造函数版本

1.Thread(ThreadStart start)

2.Thread(ParamterizedThreadStart start)

区别在于第一个构造版本只能接受 不带任何参数也不带任何返回值的方法

如:

void Method()
{
    //do things here
}

这样的方法。

第二个构造版本只能接受 带一个object型参数不带任何返回值的方法

void Method(object arg)
{
   //do things here
}

这样的方法,调用的时候 这样进行传参即可 t.Start("参数"),C# 会自动对对象进行装箱操作,在具体使用中需要对其进行拆箱操作,下面来看一个例子

public class ThreadTest
    {
        public void Invoke()
        {
            Console.WriteLine ("Main thread is running,thread Id is: {0}",Thread.CurrentThread.ManagedThreadId);

            Thread t = new Thread (new ThreadStart (Method));
            Thread t2 = new Thread (new ParameterizedThreadStart (Method2));
            t.Start ();
            t2.Start ("hello thread with paramter.");
            Thread.Sleep (1000);
            Console.WriteLine ("Main thread is ending.");
        }

        private void Method()
        {
            Console.WriteLine ("thread is running,thread Id is: {0}",Thread.CurrentThread.ManagedThreadId);
        }

        private void Method2(object arg)
        {
            Console.WriteLine ((string)arg);
            Console.WriteLine("thread is running,thread Id is: {0}",Thread.CurrentThread.ManagedThreadId);
        }
    }


调用它

class MainClass
    {
        public static void Main (string[] args)
        {
            ThreadTest test = new ThreadTest ();
            test.Invoke ();
            Console.ReadKey ();
        }
    }

会看到两个方法在不同线程中运行,此处Thread.Sleep(1000) 是线程类提供的静态方法,可以让线程暂停1000毫秒。

那么如果需要线程方法有返回值,又该怎么办呢?别急,有办法的,这时候我们只需要一个辅助包装类

public class Wrap
    {
        public string Result{ get; set; }
        public void WrapMethod(object arg)
        {
            Console.WriteLine("thread is running,thread Id is: {0}",Thread.CurrentThread.ManagedThreadId);
            string s = (string)arg;
            s = s.ToLower ();
            Result = s;
        }
    }
Wrap wrap = new Wrap();
Thread t3 = new Thread (new ParameterizedThreadStart (wrap.WrapMethod));
t3.Start("Hello Thread With Arg.");

然后通过wrap的Result属性取回结果即可。

原文地址:https://www.cnblogs.com/yayaxxww/p/3544362.html