实施线程时产生疑问 [英] Doubt while implementing Threading

查看:50
本文介绍了实施线程时产生疑问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我正在我的项目中实现线程.
我正在做这样的事情.
这是我的工人班:

 公共  class 测试
{
公共 test(){};
公共 无效 DoWork(字符串 abc)
{
布尔 result =  false ;
尝试
{
// 做一些工作
结果=  true ;
}
捕获(){}
返回结果;
}
} 



这是我的威胁类:

 公共  class 线程化
{
测试objTest = ;
公共 threading()
{
objTest =  objTest();
}

公共 无效 ThreadCall()
{
线程myThread =  Thread( ParameterizedThreadStart(objTest.DoWork));
myThread.Start(" );
}
} 



这只是一个示例,我的DoWork方法将在许多线程上运行.

现在我想知道有什么方法可以在线程完成后从DoWork方法返回bool值.
我们是否可以从在线程下运行的方法返回值,因为我没有看到Thread.Start()方法返回任何值,如果可以,那么我们如何获取该值.

谢谢,
Nagendra.

解决方案

如果要从线程中反馈信息,请使用BackgroundWorker,它更容易并且所有部分都可供您使用.

或者,如果您仍然坚持为此目的使用线程,则必须具有某种共享数据结构,并确保在运行多个线程并使用相同数据的情况下进行同步他们正确.

找到了一个可以很好地解释的程序: C#Worker Thread Starter Kit [ BackgroundWorker

是一件方便的事情.

希望这会有所帮助

干杯


Hi All,

I am implementing threading in my project.
I am doing something like this.
This is my worker class:

public class test
{
public test(){};
public void DoWork(string abc)
{
bool result = false;
try
{
//do some work
result = true;
}
catch(){}
return result;
}
}



This is my threaing class:

public class threading
{
test objTest = null;
public threading()
{
objTest = new objTest();
}

public void ThreadCall()
{
Thread myThread = new Thread(new ParameterizedThreadStart(objTest.DoWork));
myThread.Start("abc");
}
}



This is just a sample, my DoWork method will run for many threads.

Now i want to know is there any way available by which i can return a bool value from DoWork method after completion of thread.
Can we return a value from a method which is running under a thread because i didn''t saw Thread.Start() method returning anything, if yes then how can we fetch that value.

Thanks,
Nagendra.

Use BackgroundWorker if you want feedback form your thread, it''s easier and has all the parts ready for you to use.


Or, if you would still insist on using Threads for this purpose, you would have to have a shared data structure of some kind and make sure that with multiple threads running and using the same data, you synchronise them properly.

Found this one that explains quite nicely :
C# Worker Thread Starter Kit[^]

Otherwise, as Mehdi already pointed out,

BackgroundWorker

is a nice handy thing.

Hope this helps

Cheers


这篇关于实施线程时产生疑问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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