如何使用线程启动带参数的方法 [英] How Start Methods With Arguments Using Thread

查看:31
本文介绍了如何使用线程启动带参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于在 C# 中创建和启动新线程,我们的行为如下:

For Create And Start New Threads In C# We Act Like Below :

using System.Threading;

Thread thread = new Thread(new ThreadStart(WorkThreadFunction));
thread.Start();

public void WorkThreadFunction()
{
  //Stuff Here
}

但是带参数的方法呢.
对于这些方法,下面的代码有错误.

but what about methods with arguments.
for these methods the codes below have an error.

using System.Threading;

int a = 5;
int b = 6;
Thread thread = new Thread(new ThreadStart(WorkThreadFunction(a, b)));
thread.Start();


public void WorkThreadFunction(int a, int b)
{
  //Stuff Here
}

错误:

需要的方法名称

我需要将这些参数传递给那个方法!
解决办法是什么?

i need to pass those parameters to that method!
what is the solution?

提前致谢

推荐答案

使用 lambda 表达式来封装带参数的方法调用:

Use a lambda expression for encapsulating the invocation of your method with parameters:

Thread thread = new Thread(new ThreadStart(() => WorkThreadFunction(a, b)));

这篇关于如何使用线程启动带参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆