简体   繁体   English

C#winforms带参数的方法上的多线程

[英]C# winforms multithread on method with parameters

I have a method with 3 parameters on which I would like to create for it a thread. 我有一个带有3个参数的方法,我想在上面创建一个线程。 I know how to create a thread for a method without any paremeters and with object type parameter. 我知道如何为没有任何参数和对象类型参数的方法创建线程。 The method header is: 方法头是:

public void LoadData(DataGridView d, RadioButton rb1, RadioButton rb2){
//} 

In addition to Tzah answer, you do not mention the thread life time and management. 除了Tzah的答案外,您还没有提及线程的生存时间和管理。 This is a good place to think about it - As long as you write high quality code.. 这是一个考虑的好地方-只要编写高质量的代码即可。

If you use thread from threadpool with 3 params and more, using my previous answer: C# - ThreadPool QueueUserWorkItem Use? 如果您使用具有3个或更多参数的线程池中的线程 ,请使用我以前的答案: C#-ThreadPool QueueUserWorkItem使用吗?

If you are using .Net 4.0+ consider using Tasks 如果您使用的是.Net 4.0+,请考虑使用“任务”

You can use Lambda Expression like this: 您可以像这样使用Lambda表达式

new Thread(() => LoadData(var1, var2, var3)).Start();

or 要么

Thread T1 = new Thread(() => LoadData(var1, var2, var3));
T1.Start();

As Tzah's answer will definitely work, the recommanded way of using threads in the .NET Framework now resides with the Task Parallel Library . 由于Tzah的答案肯定会起作用,因此.NET Framework中使用线程的推荐方法现在驻留在Task Parallel Library The TPL provided an abstraction over the ThreadPool , which manages a pool of threads for us to use instead of creating and destroying, which has a non-neglectibale cost. TPL在ThreadPool提供了一个抽象, ThreadPool管理着一个供我们使用的线程池,而不是创建和销毁线程,这具有不可忽视的成本。 They may not be suitable for all sorts of offload work (like very long running cpu consuming tasks), but they will definitely cover most cases. 它们可能不适合所有类型的卸载工作(例如非常长时间运行的cpu消耗任务),但是它们肯定会涵盖大多数情况。

An example equivalent to your request using the TPL would be to use Task.Run : 与您使用TPL的请求等效的示例是使用Task.Run

Task task = Task.Run(() => LoadData(var1, var2, var3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM