如果我有至少2个类。一个类创建位图,另一个绘制UI形式的位图。我想问你是否有任何变量可以从UIClass传送到除整个窗体或任何控件以外的GeneratorClass。我更愿意将“线程”作为属性从UIClass传输到GeneratorClass,并且在GeneratorClass中,我可以通过在UIThread中调用来创建图像。如何让线程在DotNet中调用
我知道:
Control.Invoke(Delegate, Parameters)
或者在WPF
Control.Dispatcher(Delegate, Parameters)
我也知道
System.Threading.Thread(ThreadStart)
我宁愿只有一个 “线程变量” 一起工作启动调用或使用Dispatcher留在WPF和WinForms和GeneratorClass中使用相同的线程。
感谢你的想法(在VB.Net首选)
*我工作的回答*
使用共享Threading.SynchronizationContext.Current
接收当前的UI线程。然后使用 GuiThread.Send(AddressOf MyMethode, MyParameters)
在UI线程中工作。
Private Sub CreateTestImage()
'This methode is needed to work in Ui Thread
Dim SyncContext As Threading.SynchronizationContext = Threading.SynchronizationContext.Current 'Read current UI Thread and store it to variable
If Me._UseMultiThreading = True Then
'call methode WITH multthreading
Dim ThS As New Threading.ParameterizedThreadStart(AddressOf CreateTestImageAsync)
Dim Th As New Threading.Thread(ThS)
Th.SetApartmentState(Threading.ApartmentState.STA)
Th.Start(SyncContext)
Else
'call methode WITHOUT multthreading
Call CreateTestImageAsync(SyncContext)
End If
End Sub
了Methode螺纹:
Private Sub CreateTestImageAsync(ByVal obj As Object)
'Callback is only supporting As Object.
'Cast it back the the SynchronizationContext
Dim GuiThread As Threading.SynchronizationContext = CType(obj, Threading.SynchronizationContext)
'Do some stuff
GuiThread.Send(AddressOf ImageCreated, ImgInfo) 'Call methode in UI thread
End Sub