Subscribe to The Madman Scribblings        RSS Feed

Tasks + Events + RX Schedulers = Concurrency Heaven

Icon Leave Comment
Tasks + Events + RX Schedulers = Concurrency Heaven

Demo: Of using a Task, some Events and an IScheduler (provide via the latest version of RX)
Imports System.Threading.Tasks
Imports System.Concurrency.TaskPoolScheduler
Imports System.Threading
Imports System.Concurrency

In this case the task is will a clock that you start and stop.
Public Class AnExampleClassObject
  Protected cts As New CancellationTokenSource
  Protected ct As CancellationToken
  Protected t As Task

  Public Event Updated(Sender As Object, e As UpdateArgs)
  Public Event StopEvent()
  Public Event StartEvent()

  Public Sub New()

  End Sub

  Public Sub Start()
    ct = cts.Token
    t = Task.Factory.StartNew(AddressOf TaskToDo, ct)
    RaiseEvent StartEvent()
  End Sub

  Public Sub [Stop]()
    RaiseEvent StopEvent()
  End Sub

  Public ReadOnly Property Status() As TaskStatus
      Return t.Status
    End Get
  End Property
  Private Sub DoUpdate(ByVal UpdateString As String)
    RaiseEvent Updated(Me, New UpdateArgs(UpdateString))
  End Sub

  Protected Friend Sub TaskToDo()
    While ct.IsCancellationRequested = False
    End While
  End Sub
End Class

The Updated Event use some custom args, to pass the updated text along.

Public Class UpdateArgs
  Inherits EventArgs
  Protected _text As String
  Public Sub New(t As String)
    _text = t
  End Sub

  Public ReadOnly Property Text() As String
      Return _text
    End Get
  End Property
End Class

Now let's plug it all together

Imports System.Concurrency

Public Class Form1
  Protected Scheduler As New ControlScheduler(Me)
  Protected Guard As Boolean = False
  Protected WithEvents MyObject As AnExampleClassObject

  Private Sub shtiToDo()
    MyObject = New AnExampleClassObject()
  End Sub

  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles StartStopButton.Click
    If Guard AndAlso MyObject IsNot Nothing Then
      Threading.ThreadPool.QueueUserWorkItem(New Threading.WaitCallback(AddressOf shtiToDo))
    End If
  End Sub

  Protected Sub onstart() Handles MyObject.StartEvent
    Guard = True
    Scheduler.Schedule(Sub() Me.StartStopButton.Text = "Cancel")
  End Sub

  Protected Sub onstop() Handles MyObject.StopEvent
    Guard = False
    Scheduler.Schedule(Sub() Me.StartStopButton.Text = "Run")
  End Sub

  Protected Friend Sub MyUpdateRoutine(sender As Object, e As UpdateArgs) Handles MyObject.Updated
    Scheduler.Schedule(Sub() Me.ClockDisplay.Text = e.Text)
  End Sub
End Class

  • Works with "Normal" Threads When I used the ThreadPool
  • Works with Tasks
  • The Form Updating was achieved via ControlScheduler An IScheduler
  • Also works via Lambda for the Event handling.

So that's about 80 Lines of Code and not single invoke in sight.

0 Comments On This Entry


Search My Blog

Recent Entries

Recent Comments