开发者

Threading: Call a delegate from a separate thread (VS2010)

So, I'm having troubles implementing a separate thread. This is because I have a simple class, and in it I start a new thread. So, as it is not any form, I haven't found any way to make it call the func开发者_开发问答tion in the UI Thread.

So, I cannot use the Invoke method. Is there any way to call a function from another thread?


I am going to assume that you have events exposed from your class and that you want the event handlers to execute on a UI thread. I suppose you could have a callback that the caller specifies as well. Either way the pattern I will describe below will work in both cases

One way to make this happen is to have your class accept an ISynchronizeInvoke instance. Form and Control instances implement this interface so a reference to one of them could be used. You could make it a convention that if the an instance is not specified then event handlers executed by raising events on your class would execute in the worker thread instead of the thread hosting the ISynchronizeInvoke instance (usually a form or control).

Public Class YourClass
  Private m_SynchronizingObject As ISynchronizeInvoke = Nothing

  Public Sub New(ByVal synchronizingObject As ISynchronizeInvoke)
    m_SynchronizingObject = synchronizingObject
  End Sub

  Public Property SynchronizingObject As ISynchronizeInvoke
    Get
      Return m_SynchronizingObject
    End Get
    Set(ByVal value As ISynchronizeInvoke)
      m_SynchronizingObject = value
    End Set
  End Property

  Private Sub SomeMethodExecutingOnWorkerThread()
    RaiseSomeEvent()
  End

  Private Sub RaiseSomeEvent()
    If Not SychronizingObject Is Nothing AndAlso SynchronizingObject.InvokeRequired Then
      SynchronizingObject.Invoke(New MethodInvoker(AddressOf RaiseSomeEvent)
    End If
    RaiseEvent SomeEvent
  End Sub

End Class

The first thing to notice is that you do not have to specify a synchronizing object. That means you do not have to have a Form or Control reference. If one is not specified then SomeEvent will be raised on the worker thread. This is the same pattern that is used in the System.Timers.Timer class.


Try to expose some events in your class, fire them when you need to notify your UI and finally make your UI Component register to these events, when the event is fired, the listener methods will be executed. there you can use Control.Invoke or Control.BeginInvoke to execute your code on the UI thread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜