[REPOST]在另一个类的新线程中运行Shared Sub [英] [REPOST] Run Shared Sub In new thread from another Class
问题描述
当我尝试从我的form1应用程序中的另一个类运行共享子时,我似乎遇到了问题。直接调用时代码完美无缺,但是当我尝试多线程时,form1上的控件不会更新。
共享函数和sub
I seem to be having problems when trying to run the shared sub from another class in my form1 application. The code works flawless when its called directly but when i try to multi thread the controls on form1 will not update.
The shared function and sub
Public Shared Function FileCount(PathName As String) As Long
Try
Dim FSO As New FileSystemObject
Dim fld As Folder
If FSO.FolderExists(PathName) Then
fld = FSO.GetFolder(PathName)
FileCount = fld.Files.Count
End If
Return FileCount
Catch ex As DirectoryNotFoundException
End Try
End Function 'Calculate File Count
Public Shared Sub StartNewScan(ByVal FilePath As String)
Dim Allfile As String = "*.*"
Dim FFcount As Long
Dim MyFolderSize As Long
Dim FullPath As String
Using fse As New FindFiles.FileSystemEnumerator(FilePath, Allfile, True)
Dim ien As IEnumerator(Of FileInfo) = fse.Matches().GetEnumerator()
ien.Dispose()
For Each fi As FileInfo In fse.Matches()
FFcount += CStr(FileCount(fi.DirectoryName)).Length
Form1.Label3.Text = CStr( "File Count:" & FFcount)
MyFolderSize += fi.Length
FullPath = fi.FullName
Form1.Label4.Text = "File Path:" & FullPath
Next
End Using
End Sub
我试图在form1中调用共享子,就像这样
I am trying to call the shared sub in form1 like so
Dim StartSharedSub as new threading.thread(addressof Startnewscan)
startsharedsub.start()
我知道代理人,在我的情况下可能需要使用它来更新我的UI控件,但我很困惑如何在我的情况下实现它。
提前谢谢
I am aware of delegates and that it may be necessary in my case to use that to update my UI controls but I am confused how to implement it in my case.
thank you in advance
推荐答案
不要在多个论坛中回答相同的问题。它恳求工作,不允许协作回答。
Don't past the same question in multiple forums. It supplicates work and does not allow for a collaborative answer.
你需要学习如何使用线程和UI。
您无法从非UI线程调用与UI相关的任何内容。相反,您需要使用Invoke
或
System.Windows.Threading的方法
。 Dispatcher
(对于Forms或WPF)或System.Windows.Forms.Control
(仅限表单)。
您将在我过去的答案中找到有关其工作原理和代码示例的详细说明:
Control.Invoke()与Control.BeginInvoke() [ ^ ],
使用Treeview扫描仪和MD5的问题 [ ^ ]。
另请参阅有关线程的更多参考资料:
如何让keydown事件在不同的操作上运行vb.net中的线程 [ ^ ],
在启用禁用+多线程后控制事件未触发 [ ^ ]。
-SA
You need to learn how to work with threads and UI.
You cannot call anything related to UI from non-UI thread. Instead, you need to use the methodInvoke
orBeginInvoke
ofSystem.Windows.Threading.Dispatcher
(for both Forms or WPF) orSystem.Windows.Forms.Control
(Forms only).
You will find detailed explanation of how it works and code samples in my past answers:
Control.Invoke() vs. Control.BeginInvoke()[^],
Problem with Treeview Scanner And MD5[^].
See also more references on threading:
How to get a keydown event to operate on a different thread in vb.net[^],
Control events not firing after enable disable + multithreading[^].
—SA
这篇关于[REPOST]在另一个类的新线程中运行Shared Sub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!