关于C#创建线程的线程函数怎么传参数

.Net技术 码拜 7年前 (2017-04-12) 805次浏览
查到创建线程是这样的格式:

public static void ThreadProc()
 {}
public static void Main()
 {
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
}

关于ThreadProc函数,假如想给他传个参数,是不是只能在public 类里定义public static 数据的方法解决?能不能想想办法按值传递局部变量的方法,主要是想传递的参数更容易销毁。

解决方案

5

public static void ThreadProc()
{
}
public static void ThreadProc(int x, int y)
{
}
Thread t = new Thread(() =>
{
    ThreadProc();
    int x = 1;
    int y = x + 1;
    ThreadProc(x, y);
});
t.Start();

你可以随便写任意的语句,甚至可以调用“外层”的变量,例如

string a = "张三";
Thread t = new Thread(() =>
{
    ThreadProc();
    int x = 1;
    int y = x + 1;
    ThreadProc(x, y);
    int z = a.Length;
});
t.Start();

c# 是很优雅的。不是只能简单暴力地调用 ThreadProc 一个函数的。

5

本人现在也用的是楼上的方法

int x = 0;
(new Thread(() => { Test(x); })).Start();
void Test(int x)
{
}

10

引用:
Quote: 引用:

Console.Write(“The Area Of Circle with a Diameter of {0} is {1}”Diameter,Diameter*Math.PI);

write函数没有输出,即使让主线程暂停也没输出。
第二行 new Thread 编译不了

手写代码漏了东西

   Thread myThread = new Thread(new ParameterizedThreadStart(ThreadFunc));
        myThread.Start(2);
    static void ThreadFunc(object param)
    {
        int value = (int)param;
        Console.WriteLine("Thread param: "+ value.ToString());
        
    }

3楼的当然更简洁


CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于C#创建线程的线程函数怎么传参数
喜欢 (0)
[1034331897@qq.com]
分享 (0)