Task Constructor (Action(Of Object), Object)

 

Initializes a new Task with the specified action and state.

Namespace:   System.Threading.Tasks
Assembly:  mscorlib (in mscorlib.dll)

Public Sub New (
	action As Action(Of Object),
	state As Object
)

Parameters

action
Type: System.Action(Of Object)

The delegate that represents the code to execute in the task.

state
Type: System.Object

An object representing data to be used by the action.

Exception Condition
ArgumentNullException

The action argument is null.

Rather than calling this constructor, the most common way to instantiate a Task object and launch a task is by calling the static TaskFactory.StartNew(Action(Of Object), Object) method. The only advantage offered by this constructor is that it allows object instantiation to be separated from task invocation.

The following example defines an array of 6-letter words. Each word is then passed as an argument to the Task(Action(Of Object), Object) constructor, whose Action(Of T) delegate scrambles the characters in the word, then displays the original word and its scrambled version.

Imports System.Collections.Generic
Imports System.Threading.Tasks

Module Example
   Public Sub Main()
      Dim tasks As New List(Of Task)()
      Dim rnd As New Random()
      Dim lockObj As New Object()
      Dim words6() As String = { "reason", "editor", "rioter", "rental",
                                 "senior", "regain", "ordain", "rained" }

      For Each word6 in words6
         Dim t As New Task( Sub(word)
                               Dim chars() As Char = word.ToString().ToCharArray()
                               Dim order(chars.Length - 1) As Double
                               SyncLock lockObj
                                  For ctr As Integer = 0 To order.Length - 1
                                     order(ctr) = rnd.NextDouble()
                                  Next
                               End SyncLock
                               Array.Sort(order, chars)
                               Console.WriteLine("{0} --> {1}", word,
                                                 New String(chars))
                            End Sub, word6)
         t.Start()
         tasks.Add(t)
      Next
      Task.WaitAll(tasks.ToArray())
   End Sub
End Module
' The example displays output like the following:
'       regain --> irnaeg
'       ordain --> rioadn
'       reason --> soearn
'       rained --> rinade
'       rioter --> itrore
'       senior --> norise
'       rental --> atnerl
'       editor --> oteird

Universal Windows Platform
Available since 8
.NET Framework
Available since 4.0
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 5.0
Windows Phone Silverlight
Available since 8.0
Windows Phone
Available since 8.1
Return to top
Show: