我正在尝试从 UWP 类库后台任务引发事件,但我需要在计划使用类库的 UWP 应用中的主 UI 线程上封送它。 不过,我正在寻找一种从后台任务中封送它的方法。 我浏览了几篇文章,包括这篇:在主 UI 线程上引发 .NET 中的事件但这对我来说没有意义。 任何人都可以帮我完成以下代码吗?
Private ReceiveTask As New Task(Sub()
Dim InStream As Stream = CSocket.InputStream.AsStreamForRead
While killswitch = False
Try
Dim Reader As StreamReader = New StreamReader(InStream)
Dim DataText As String = ""
While Reader.Peek <> -1
DataText &= Convert.ToChar(Reader.Read)
End While
RaiseEvent DataReceived(DataText)
Catch ex As Exception
RaiseEvent SocketError("Receiving", ex.Message)
End Try
End While
End Sub)
感谢jmcilhinney,下面的代码可以工作!
Private ReceiveTask As New Task(Sub()
Dim InStream As Stream = CSocket.InputStream.AsStreamForRead
While killswitch = False
Try
Dim Reader As StreamReader = New StreamReader(InStream)
If Reader.Peek <> -1 Then
DataText = ""
While Reader.Peek <> -1
DataText &= Convert.ToChar(Reader.Read)
End While
uiContext.Post(AddressOf RaiseDataToUI, Nothing)
End If
Catch ex As Exception
ReceiveError = ex.Message
uiContext.Post(AddressOf RaiseErrorToUI, Nothing)
End Try
End While
End Sub)
我自己没有做过任何 UWP 开发,但我相信按照你想要的方式的正确方法是使用 SynchronizationContext
类,就像在 WPF 中一样。 原则是 SynchronizationContext.Current
属性将生成特定于线程的类实例,因此可以在 UI 线程上获取该属性的值,然后在其他位置使用该对象封送对所属线程的调用。 属性值通常在 UI 线程上创建本身的对象的构造函数中检索,例如
Imports System.Threading
Public Class SomeClass
'Get the context for the thread on which the current instance is created.
Private uiContext As SynchronizationContext = SynchronizationContext.Current
Private Sub ThisMethodIsCalledOnASecondaryThread()
uiContext.Post(AddressOf ThisMethodIsCalledOnTheUIThread, Nothing)
End Sub
Private Sub ThisMethodIsCalledOnTheUIThread(data As Object)
'Execute UI thread logic here, e.g. raise an event.
End Sub
End Class