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

谁学逆向工程 2016-10-22 06:16:05
查到创建线程是这样的格式:

public static void ThreadProc()
{}
public static void Main()
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
}
关于ThreadProc函数,如果想给他传个参数,是不是只能在public 类里定义public static 数据的方法解决?能不能想想办法按值传递局部变量的方法,主要是想传递的参数更容易销毁。
...全文
213 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
xian_wwq 2016-10-24
  • 打赏
  • 举报
回复
引用 2 楼 xiaoyuanyuan2009 的回复:
[quote=引用 1 楼 xian_wwq 的回复:] Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI);
write函数没有输出,即使让主线程暂停也没输出。 第二行 new Thread 编译不了[/quote] 手写代码漏了东西


   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楼的当然更简洁
白衣如花 2016-10-23
  • 打赏
  • 举报
回复
我现在也用的是楼上的方法
int x = 0;
(new Thread(() => { Test(x); })).Start();

void Test(int x)
{
}
  • 打赏
  • 举报
回复
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 一个函数的。
谁学逆向工程 2016-10-22
  • 打赏
  • 举报
回复
引用 1 楼 xian_wwq 的回复:
Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI);
write函数没有输出,即使让主线程暂停也没输出。 第二行 new Thread 编译不了
xian_wwq 2016-10-22
  • 打赏
  • 举报
回复
ParameterizedThreadStart可以传参

ParameterizedThreadStart threadStart=new ParameterizedThreadStart(Calculate)
Thread thread=new Thread() ;
thread.Start(0.9);
public void Calculate(object arg)
{
double Diameter=double(arg);
Console.Write("The Area Of Circle with a Diameter of {0} is {1}"Diameter,Diameter*Math.PI);
}

110,566

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧