Windows窗体中的Mulithreading [英] Mulithreading in windows forms

查看:99
本文介绍了Windows窗体中的Mulithreading的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何在Windows窗体中应用多线程.我只需要在2个列表框中并行打印1到100个数字.该怎么做?

Hi,

How to apply multithreading in a windows forms.I just need to print 1 to 100 numbers parallely in 2 listboxes.How to do that?

推荐答案

我建​​议您一些文章在这里
多线程无效 [
I suggested you some articles here
Multithreading doesn''t work[^]
Did you try anything?


是的,先生.但是那篇文章与控制台应用程序有关.
Yes sir..but that articles are related with console applications..


您可以执行以下操作:

You could do something like:

System.Threading.Tasks.Parallel.For(0, 100, i =>
        {
            listBox1.Items.Add(i)
            listBox2.Items.Add(i)
        });



但是,我会事先告诉您,这个答案当前是错误的,因为它在尝试访问列表框时将失败,因为可能需要使用...
来访问它们.



But I will tell you up front that this answer is currently wrong because it will fail when it tries to access the listboxes because they will likely need to be accessed by using something like ...

Private Delegate Sub dlgListBox1Update(ByVal text As String)
 
Sub updateListBox1(ByVal text As String)
    If ListBox1.InvokeRequired = True Then
        Dim d As New dlgListBox1Update(AddressOf updateListBox1)
        ListBox1.Invoke(d, text)
    Else
        ListBox1.Items.Add(text)
    End If
End Sub

Private Delegate Sub dlgListBox2Update(ByVal text As String)
 
Sub updateListBox2(ByVal text As String)
    If ListBox2.InvokeRequired = True Then
        Dim d As New dlgListBox2Update(AddressOf updateListBox2)
        ListBox2.Invoke(d, text)
    Else
        ListBox2.Items.Add(text)
    End If
End Sub

System.Threading.Tasks.Parallel.For(0, 100, i =>
        {
            updateListBox1(i.toString)
            updateListBox2(i.toString)
        });



您需要使用委托和update子例程,以确保您调整到正确的线程以实际更新列表框...这是多线程应用程序的基本挑战(以及为什么大多数示例使用控制台,以便它们能够专注于示例而不创建委托.)

当然,下一个问题是当您尝试在不同线程中更改变量时...如果使用全局变量,则需要锁定它们以确保不从多个线程中更改它们.

希望这会有所帮助.



You need to use the delegates and the update subroutines in order to ensure that you adjust to the correct thread for actually updating the listboxes ... that''s the fundamental challenge with multithreaded applications (and why most examples use the console so they can focus on the example and not creating delegates).

Of course the next problem you''ll have is when you try and change variables within your different threads ... if you use global variables then you''ll need to lock them to ensure you don''t change them from multiple threads.

Hope this helps.


这篇关于Windows窗体中的Mulithreading的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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