且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#线程方法返回一个值?

更新时间:2023-02-14 16:55:50

不仅的ThreadStart 预期void的方法,它也希望他们不要带任何参数!你可以把它包装在一个lambda,匿名委托,或命名静态函数



下面是这样做的一种方式:

 字符串资源= NULL; 
螺纹newThread =新的Thread(()=> {!天下解析度=的sayHello();});
newThread.Start();
newThread.Join(1000);
Console.Writeline(RES);

下面是另一个语法:

 发newThread =新主题(委托(){的sayHello(世界!);}); 
newThread.Start();



第三个语法(以命名函数)是最无聊的:

  //定义一个包装功能
静态无效WrapSayHello(){
的sayHello(世界!);
}

//从别的地方
线程调用它newThread =新主题(WrapSayHello);
newThread.Start();


Possible Duplicate:
Access return value from Thread.Start()'s delegate function

public string sayHello(string name)
{
    return "Hello ,"+ name;
}

How can i use this method in Thread?

That ThreadStart method just accept void methods.

I'm waiting your helps. Thank you.

Not only does ThreadStart expect void methods, it also expect them not to take any arguments! You can wrap it in a lambda, an anonymous delegate, or a named static function.

Here is one way of doing it:

string res = null;
Thread newThread = new Thread(() => {res = sayHello("world!");});
newThread.Start();
newThread.Join(1000);
Console.Writeline(res);

Here is another syntax:

Thread newThread = new Thread(delegate() {sayHello("world!");});
newThread.Start();

The third syntax (with a named function) is the most boring:

// Define a "wrapper" function
static void WrapSayHello() {
    sayHello("world!);
}

// Call it from some other place
Thread newThread = new Thread(WrapSayHello);
newThread.Start();