2011-05-31 63 views
1

如果我有至少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 

回答

2

你会传递当前SynchronizationContext到线程。 在你的线程会是这个样子:

void ThreadMethod(object parameter) 
{ 
    var context = (SynchronizationContext)parameter; 

    context.Send((s) => TheMethodYouWantToRunOnTheUiThread(), null); 
} 

您将开始您的线程是这样的:

var newThread = new Thread(ThreadMethod); 
newThread.Start(SynchronizationContext.Current); 

这是在C#中,但我认为你可以翻译它。

顺便说一句:这是BackgroundWorker class用于将事件ProgressChangedCompleted编组到UI线程的非常相同的机制。有关该主题的更多信息,请参阅here

相关问题