다음을 통해 공유


Async.SwitchToContext 메서드(F#)

업데이트: 2010년 7월

동기화 컨텍스트 개체의 Post 메서드를 사용하여 계산을 실행하는 비동기 계산을 만듭니다.

네임스페이스/모듈 경로: Microsoft.FSharp.Control

어셈블리: FSharp.Core(FSharp.Core.dll)

// Signature:
static member SwitchToContext : SynchronizationContext -> Async<unit>

// Usage:
Async.SwitchToContext (syncContext)

매개 변수

  • syncContext
    형식: SynchronizationContext

    게시된 계산을 허용하는 동기화 컨텍스트입니다.

반환 값

syncContext 컨텍스트를 사용하여 실행되는 비동기 계산입니다.

설명

syncContext가 null이면 비동기 계산은 Async.SwitchToThreadPool과 같습니다.

예제

다음 코드 예제에서는 Async.SwitchToContext를 사용하여 UI 스레드를 전환하여 UI를 업데이트하는 방법에 대해 설명합니다. 이 경우 계산의 완료 상태를 나타내는 진행률 표시줄이 업데이트됩니다.

open System.Windows.Forms

let form = new Form(Text = "Test Form", Width = 400, Height = 400)
let syncContext = System.Threading.SynchronizationContext.Current
let button1 = new Button(Text = "Start")
let label1 = new Label(Text = "", Height = 200, Width = 200,
                       Top = button1.Height + 10)
form.Controls.AddRange([| button1; label1 |] )

type invokeFunction = delegate of unit -> unit

let async1(syncContext, form : System.Windows.Forms.Form) =
    async {
        let label1 = form.Controls.[1]
        // Do something.
        do! Async.Sleep(1000)

        // Switch to the UI thread and update the UI.
        do! Async.SwitchToContext(syncContext)

        let threadNumber = System.Threading.Thread.CurrentThread.ManagedThreadId
        label1.Text <- label1.Text + sprintf "On the UI Thread [%d]\n" threadNumber

        // Switch back to the thread pool.
        do! Async.SwitchToThreadPool()
        // Do something.
        do! Async.Sleep(1000)

        let threadNumber = System.Threading.Thread.CurrentThread.ManagedThreadId

        // When on a thread pool thread, use Control.Invoke to update UI.
        label1.Invoke(new invokeFunction(fun () -> 
            label1.Text <- label1.Text +
                       sprintf "Switched to thread pool [%d]\n" threadNumber)) |> ignore
    }

let buttonClick(sender:obj, args) =
    let button = sender :?> Button
    Async.Start(async1(syncContext, button.Parent :?> Form))

    let threadNumber = System.Threading.Thread.CurrentThread.ManagedThreadId
    label1.Text <- sprintf "Started asynchronous workflow [%d]\n"  threadNumber
    ()

button1.Click.AddHandler(fun sender args -> buttonClick(sender, args))
Application.Run(form)

플랫폼

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

버전 정보

F# 런타임

지원되는 버전: 2.0, 4.0

Silverlight

지원되는 버전: 3

참고 항목

참조

Control.Async 클래스(F#)

Microsoft.FSharp.Control 네임스페이스(F#)

변경 기록

날짜

변경 내용

이유

2010년 7월

코드 예제를 추가했습니다.

향상된 기능 관련 정보