在.net中实现多线程有哪些不同的方法

发布于 2024-08-28 00:53:58 字数 213 浏览 7 评论 0原文

我已经与多线程斗争了几天。

我不明白多线程有什么不同的方式。我读过一些关于backgroundWorker的内容,一些关于创建线程对象的内容。 昨天我在delegate示例中看到通过调用BeginInvoke来实现多线程。

我不明白这些不同的多线程方式还是在相同的后台类上工作相同。 请帮我弄清楚。

I have been fighting with multi threading for few days.

I dont understand what are different ways of multithreading. I have read little bit about backgroundWorker, little bit about creating an object of thread.
Yesterday I saw in delegate example to implement multithreading by calling BeginInvoke.

I dont understand are these different ways of multithreading or are same working on same background class.
Please help me in making it clear to me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷夜 2024-09-04 00:53:58

任何没有 GUI 的线程都是后台工作者。
在 dot net 上使用线程的常见方法是创建一个线程对象并为其提供一个线程 main 方法,因此该函数将在后台执行
首先,我认为您应该阅读以下书籍,以获得有关该主题的更深入的知识

  • .NET 多线程
  • C# 线程手册

另外,关于 GUI 应用程序,如 WPF 或 win 表单应用程序,唯一可以更改 gui 元素的线程是主线程(gui线程),所以你应该使用这个线程使用begininvoke并在那里放置一个回调来更改gui,否则你会得到一个无效的操作异常。

使用线程的另一种方法是使用 .net 的线程池,如下所示

   ThreadPool.QueueUserWorkItem(new WaitCallback(delegateMethod), data);

 private void delegateMethod(object data){
   //some stuff
 }

any thread without a GUI is a background worker.
on dot net the common way to use threads is by creating a thread object and give it a thread main method so, this function will be executed on background
firt i think you should read the following books to get a deeper Knowledge on the subject

  • .NET Multithreading
  • C# Threading Handbook

in addition on a GUI app, like WPF or win form app, the only thread that can change the gui elements is the main thread (gui thread), so you should use begininvoke using this thread and put there a callback to change the gui, otherwise you get an invalid operation exception.

another way to use thread would be using the thread pool of .net like these

   ThreadPool.QueueUserWorkItem(new WaitCallback(delegateMethod), data);

 private void delegateMethod(object data){
   //some stuff
 }
别把无礼当个性 2024-09-04 00:53:58

首先,我要说的是,除非绝对必要,否则不要使用多线程。尝试以最熟练的方式避免和优化代码将在某种程度上取得最佳效果,因为您将避免多线程麻烦。

其次, BackgroundWorker 类是一个好的开始。您需要实例化与需要运行的线程一样多的实例。对于它们中的每一个,您都必须对其 DoWork 进行编码() 方法。当您通过调用 启动其操作时,将调用此方法BackgroundWorker.RunWorkerAsync() 方法。您想要放置在 DoWork() 事件中的代码是当应用程序的主线程忙于其他事情时应在后台异步运行的代码。另外两个事件: ProgressChanged()RunWorkerCompleted() 用于 < a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.reportprogress.aspx" rel="nofollow noreferrer">ReportProgress() 或定义要执行的操作当线程完成其工作时,无论它是什么(异常、正确结束等),我大部分时间都使用BackgroundWorker,因为以我的拙见,它是最简单的使用方式。

第三,您可以使用 System.Threading.Thread 类。它比仅定义 DoWork() 事件并通过调用另一个方法使其发生要复杂一些。您必须熟悉代理。简而言之,委托是用于在后台执行某些工作的方法或函数类型。至于这些委托,你可能有多个相同委托类型的方法,正如我刚才所说,委托是方法类型。您可能有多个代理。您也可以将其视为方法签名。然后,当需要使用它时,您必须引用所需委托的方法。使用 System.Threading.Thread 类,您需要注意 ThreadStart 委托

delegate void DoWork(object sender);

private void btnProcessWork_Click(object sender, EventArgs e) {
    DoWork doWork = SimpleDoWorkMethod;
    // Then start using the delegate.
    Thread t = new Thread(new ThreadStart(doWork));
    t.Start(); // Launch the thread in background...
    // Do something else while the thread is working !!!
}

private void SimpleDoWorkMethod(object s) {
    // Do some work here...
}

第四,将委托视为一个事件,因为事件是基于委托的。事实上,您提供了一个用于处理事件的方法,例如 Button_Click()。要以编程方式将 btnProcess.Click 事件与 btnProcess_Click() 方法关联,您需要编写:

btnProcess.Click += new EventHandler(btnProcess_Click);

您在这里所做的就是使 btnProcess.Click 事件引用您的 btnProcess_Click() 方法。请注意 EventHandler 委托和 ThreadStart 委托。它们的目的完全相同,但针对两种不同的现实(GUI 事件响应和多线程)。

第五,不要忘记在访问变量之前锁定它,而另一个变量可能想同时访问它,然后抛出跨线程或类似的异常,这甚至对于原始类型来说也是如此,但更具体地说对于集合而言,如它们不是线程安全的。

希望这会有所帮助! =)

First, let me say that you don't do multithreading unless it is absolutely necessary. Trying to avoid and optimize your code in the most proficient way will do somehow best, as you will avoid multhreading troubles.

Second, the BackgroundWorker class is a good start. You will need to instantiate as many instances as you require threads to be run. For each of them, you will have to code its DoWork() method. This method is called when you launch its operation by calling the BackgroundWorker.RunWorkerAsync() method. The code you want to place in the DoWork() event is the code that shall be asynchronously run in the background while your application's main thread gets busy with something else. The other two events : ProgressChanged() and RunWorkerCompleted() are used to ReportProgress() or to define what to do when the thread has done its job, whatever end it is (Exception, properly ended, etc.) I use BackgroundWorker most of the time, as it is, in my humble point of view, the simplest to be used.

Third, you can use the System.Threading.Thread class. It is a bit more complicated then just defining a DoWork() event and making it occur by calling another method. You will have to get acquainted with delegates. In short, delegates are types of method or function that are used to execute some work in the background. As for these delegates, you may have multiple methods of the same delegate type, as I just said, delegates are method types. You may have multiple references of a delegate. You may see it also as a method signature. Then, when comes the time to use it, you have to reference a method for the wanted delegate. Using the System.Threading.Thread class, you want to take an eye out on the ThreadStart delegate.

delegate void DoWork(object sender);

private void btnProcessWork_Click(object sender, EventArgs e) {
    DoWork doWork = SimpleDoWorkMethod;
    // Then start using the delegate.
    Thread t = new Thread(new ThreadStart(doWork));
    t.Start(); // Launch the thread in background...
    // Do something else while the thread is working !!!
}

private void SimpleDoWorkMethod(object s) {
    // Do some work here...
}

Fourth, think of delegates as an event, as Events are based on delegates. As a matter of fact, you provide a method that will be used to handle an event like the Button_Click(), for instance. To associate your btnProcess.Click event with your btnProcess_Click() method programmatically, you need to write:

btnProcess.Click += new EventHandler(btnProcess_Click);

What you do here is to make the btnProcess.Click event reference your btnProcess_Click() method. Notice the EventHandler delegate with the ThreadStart delegate. They serves quite the same purpose, but for two different reality (GUI event response and multithreading).

Fifth, don't forget to lock a variable before accessing it while another might want to access it at about the same time, then throwing a cross thread or so exception, and this, even for primitive types, but more specifically for collections, as they are not thread-safe.

Hope this helps a bit! =)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文