欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c#線程間傳遞參數(shù)詳解

 更新時(shí)間:2014年01月22日 09:23:51   作者:  
本篇文章主要是對(duì)c#中的線程間傳遞參數(shù)進(jìn)行了詳細(xì)的介紹,需要的朋友可以過來參考下,希望對(duì)大家有所幫助

線程操作主要用到Thread類,他是定義在System.Threading.dll下。使用時(shí)需要添加這一個(gè)引用。該類提供給我們四個(gè)重載的構(gòu)造函數(shù)(以下引自msdn)。

Thread (ParameterizedThreadStart)  初始化 Thread 類的新實(shí)例,指定允許對(duì)象在線程啟動(dòng)時(shí)傳遞給線程的委托。 
Thread (ThreadStart)  初始化 Thread 類的新實(shí)例。 

Thread (ParameterizedThreadStart, Int32)  初始化 Thread 類的新實(shí)例,指定允許對(duì)象在線程啟動(dòng)時(shí)傳遞給線程的委托,并指定線程的最大堆棧大小。 
Thread (ThreadStart, Int32)  初始化 Thread 類的新實(shí)例,指定線程的最大堆棧大小。

我們?nèi)绻x不帶參數(shù)的線程,可以用ThreadStart;帶一個(gè)參數(shù)的用ParameterizedThreadStart。帶多個(gè)參數(shù)的用另外的方法,下面逐一講述。

一、不帶參數(shù)的

復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace AAAAAA
{
    class AAA
    {
        public static void Main()
        {
            Thread t = new Thread(new ThreadStart(A));
            t.Start();

            Console.Read();
        }

        private static void A()
        {
            Console.WriteLine("Method A!");
        }
    }
}


二、帶一個(gè)參數(shù)的
由于ParameterizedThreadStart要求參數(shù)類型必須為object,所以定義的方法B形參類型必須為object。
復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace AAAAAA
{
    class AAA
    {
        public static void Main()
        {       
            Thread t = new Thread(new ParameterizedThreadStart(B));
            t.Start("B");

            Console.Read();
        }

        private static void B(object obj)
        {
            Console.WriteLine("Method {0}!",obj.ToString ());

        }
    }
}


結(jié)果顯示Method B!

三、帶多個(gè)參數(shù)的
由于Thread默認(rèn)只提供了這兩種構(gòu)造函數(shù),如果需要傳遞多個(gè)參數(shù),我們可以自己將參數(shù)作為類的屬性。定義類的對(duì)象時(shí)候?qū)嵗@個(gè)屬性,然后進(jìn)行操作。

復(fù)制代碼 代碼如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace AAAAAA
{
    class AAA
    {
        public static void Main()
        {
            My m = new My();
            m.x = 2;
            m.y = 3;

            Thread t = new Thread(new ThreadStart(m.C));
            t.Start();

            Console.Read();
        }
    }

    class My
    {
        public int x, y;

        public void C()
        {
            Console.WriteLine("x={0},y={1}", this.x, this.y);
        }
    }
}


結(jié)果顯示x=2,y=3

四、利用結(jié)構(gòu)體給參數(shù)傳值。
定義公用的public struct結(jié)構(gòu)體,里面可以定義自己需要的參數(shù),然后在需要添加線程的時(shí)候,可以定義結(jié)構(gòu)體的實(shí)例。

復(fù)制代碼 代碼如下:

//結(jié)構(gòu)體
  struct RowCol
    {
        public int row;
        public int col;
    };

//定義方法
public void Output(Object rc)
        {
            RowCol rowCol = (RowCol)rc;
            for (int i = 0; i < rowCol.row; i++)
            {
                for (int j = 0; j < rowCol.col; j++)
                    Console.Write("{0} ", _char);
                Console.Write("/n");
            }
        }

相關(guān)文章

最新評(píng)論