Share via


Async.StartImmediate Method (F#)

Runs an asynchronous computation, starting immediately on the current operating system thread.

Namespace/Module Path: Microsoft.FSharp.Control

Assembly: FSharp.Core (in FSharp.Core.dll)

// Signature:
static member StartImmediate : Async<unit> * CancellationToken option -> unit

// Usage:
Async.StartImmediate (computation)
Async.StartImmediate (computation, cancellationToken = cancellationToken)

Parameters

  • computation
    Type: Async<unit>

    The asynchronous computation to execute.

  • cancellationToken
    Type: CancellationToken

    The optional cancellation token to associate with the computation. The default is used if this parameter is not provided.

Remarks

If no cancellation token is provided then the default cancellation token is used.

Example

The following code example shows how to use Async.StartImmediate to start an asynchronous computation on the current thread. Often, an asynchronous operation needs to update UI, which should always be done on the UI thread. When your asynchronous operation needs to begin by updating UI, Async.StartImmediate is a better choice than Async.Start, which starts the asynchronous operation on a thread pool thread.


open System.Windows.Forms

let bufferData = Array.zeroCreate<byte> 100000000

let async1 (button : Button) =
     async {
       button.Text <- "Busy"
       button.Enabled <- false
       let context = System.Threading.SynchronizationContext.Current
       do! Async.SwitchToThreadPool()
       use outputFile = System.IO.File.Create("longoutput.dat")
       do! outputFile.AsyncWrite(bufferData)
       do! Async.SwitchToContext(context)
       button.Text <- "Start"
       button.Enabled <- true
     }


let form = new Form(Text = "Test Form")
let button = new Button(Text = "Start")
form.Controls.Add(button)
button.Click.Add(fun args -> Async.StartImmediate(async1 button))
Application.Run(form)

Platforms

Windows 7, Windows Vista SP2, Windows XP SP3, Windows XP x64 SP2, Windows Server 2008 R2, Windows Server 2008 SP2, Windows Server 2003 SP2

Version Information

F# Runtime

Supported in: 2.0, 4.0

Silverlight

Supported in: 3

See Also

Reference

Control.Async Class (F#)

Microsoft.FSharp.Control Namespace (F#)