C#线程方法返回一个值? [英] C# thread method return a value?

查看:200
本文介绍了C#线程方法返回一个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
从Thread.Start()的委托函数访问返回值






 公共字符串的sayHello(字符串名称)
{
返回你好,+名称;
}



我如何能在线程中使用这种方法吗?



这的ThreadStart方法只是接受无效的方法。



我在等待你的帮助。
谢谢你。


解决方案

不仅的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();

这篇关于C#线程方法返回一个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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