交叉线程查询 [英] Cross Threading Query
本文介绍了交叉线程查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您是Threading的新手,我想升级我的项目,以便当我查询我的数据库MySql和MS Sql时,我的用户界面不会挂断
我试过了Application.DoEvent,但我仍然想尝试线程它让我挑战自己
:)
所以这是我的代码
Hi am new with Threading and I want to Upgrade my Project so that when ever I Query to my Database "MySql" And "MS Sql" my UI won't hang up
I've Tried Application.DoEvent but still I want to try Threading it gives me challenge to myself
:)
so here's my Code
ListView Click Event
Dim LoadQuery As New Thread(AddressOf LoadToAnotherListView)
LoadQuery.IsBackground = True
LoadQuery.Start()
CheckForIllegalCrossThreadCalls = False
Public Sub LoadToAnotherListView
Dim count As Integer = 0
Using con As New SqlClient.SqlConnection(ConnectionString)
con.Open()
Dim Sql As String = "SELECT FirstName,LastName,MiddleName FROM contacts WHERE Gender = @Gender AND Age = @Age"
Using cmd As New SqlClient.SqlCommand(Sql, con)
cmd.Parameters.AddWithValue("@Gender", ListView1.FocusedItem.Text)
cmd.Parameters.AddWithValue("@Age", ListView1.FocusedItem.SubItems(2).Text)
cmd.CommandTimeout = 3600
cmd.CommandType = CommandType.Text
Using DataRead As SqlClient.SqlDataReader = cmd.ExecuteReader
If DataRead.HasRows Then
lblLoading.Visible = False
While DataRead.Read
count += 1
ListView2.Items.Add(Trim(DataRead(0).ToString))
ListView2.Items(ListView2.Items.Count - 1).SubItems.Add(Trim(DataRead(1).ToString))
ListView2.Items(ListView2.Items.Count - 1).SubItems.Add(Trim(Format(DataRead(2), "yyyy-MM-dd")))
End While
lblItem.Visible = True
lblItem.Text = countitem & " Item/s"
End If
DataRead.Close()
End Using
End Using
con.Close()
End Using
btnPrint.Enabled = ListView2.Items.Count > 1
End Sub
如何在不使用的情况下实施线程
CheckForIllegalCrossThreadCalls = False
它免除了 CrossThreading
PS:如果你有更好的编码方式随意发布:)
How do I Implement Threading with out using
CheckForIllegalCrossThreadCalls = False
It give exemption of CrossThreading
PS: If you have better way of my coding feel free to post :)
推荐答案
嗯,关键是你试图从一个非主要的线程中更改你的ListView2
(UI)线程 - 根本不允许。
解决方案可以是将数据库中的数据加载到新线程中的集合对象中,然后发出数据可用的信号,然后将数据添加到主线程中的ListView(使用InvokeRequired和Invoke)。
优化的另一个 点是listview的BeginUpdate和EndUpdate方法。最后你可以使用列表视图的VirtualMode。或者在sql语句结尾处使用LIMIT 100子句限制结果项的数量...
Well, the point is that you try to change yourListView2
from a thread which is not the main (UI) thread - and that's not allowed at all.
A solution could be to load the data from the database into a collection object in your new thread, then signal that the data are available, and then add the data to the ListView in the main thread (use InvokeRequired and Invoke).
Another point for optimization are the BeginUpdate and EndUpdate methods of the listview. And you could eventually use the VirtualMode of the list view. Or limit the number of result items with a LIMIT 100 clause at the end of your sql statement...
这篇关于交叉线程查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文