[英]How can I raise an event on the Main UI thread from background task in UWP APP (vb.net)
[英]Raise Event Vb.net from worker Thread
我正在尋找vb.net的控制台應用程序。 我試圖讓一個工作線程向主線程引發一個事件,以便在屏幕上顯示數據(每當工作線程完成一個循環時,單詞“ HIT”)。 我的代碼如下。
我不確定為什么,但是主線程的Private Sub CounterClass_GivingUpdate() Handles _counter.AboutToDistributeNewupdate
沒有執行。
Imports System.Threading
Module Module1
Private WithEvents _counter As CounterClass
Private trd As Thread
Sub Main()
While True
Dim s As String = Console.ReadLine()
Dim started As Boolean
Select Case s
Case "status"
WriteStatusToConsole("You typed status")
Case "startcounter"
If started = False Then
starttheThread()
started = True
WriteStatusToConsole("You Have Started The Timer")
Else
WriteStatusToConsole("YOU HAVE ALREADY STARTED THE TIMER!!!")
End If
End Select
End While
End Sub
Private Sub CounterClass_GivingUpdate() Handles _counter.AboutToDistributeNewupdate
WriteStatusToConsole("Hit")
End Sub
Private Sub starttheThread()
Dim c As New CounterClass
trd = New Thread(AddressOf c.startProcess)
trd.Start()
End Sub
Sub WriteStatusToConsole(ByVal stringToDisplay As String)
Console.WriteLine(stringToDisplay)
End Sub
End Module
Public Class CounterClass
Public Event AboutToDistributeNewupdate()
Public Sub sendStatusUpdateEvent(ByVal updatestatus As String)
RaiseEvent AboutToDistributeNewupdate()
End Sub
Public Sub startProcess()
Dim i As Int64
Do
Thread.Sleep(1000)
i = i + 1
sendStatusUpdateEvent(i.ToString)
Loop
End Sub
End Class
您的CounterClass_GivingUpdate()
僅處理_counter
變量的事件(您不使用的變量!) 。 每次您聲明新的CounterClass
它都有它自己引發的事件的實例。
您知道有兩種選擇:
選項1
為您創建的每個新CounterClass
實例訂閱事件。 意味着每次創建類的新實例時,都必須使用AddHandler
語句:
Private Sub starttheThread() Dim c As New CounterClass AddHandler c.AboutToDistributeNewupdate, AddressOf CounterClass_GivingUpdate trd = New Thread(AddressOf c.startProcess) trd.Start() End Sub
選項2
將事件標記為“ Shared
以使其可用,而無需創建該類的實例。 為此,還必須通過在方法Main()
訂閱事件來更改訂閱事件的方式:
Sub Main() AddHandler CounterClass.AboutToDistributeNewupdate, AddressOf CounterClass_GivingUpdate ...the rest of your code... End Sub Private Sub CounterClass_GivingUpdate() 'No "Handles"-statement here. WriteStatusToConsole("Hit") End Sub Public Class CounterClass Public Shared Event AboutToDistributeNewupdate() 'Added the "Shared" keyword. ...the rest of your code... End Class
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.