다음을 통해 공유


Async.SwitchToContext 메서드(F#)

동기화 컨텍스트 개체의 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()
let button1 = new Button(Text = "Start")
let label1 = new Label(Text = "", Height = 200, Width = 200,
                       Top = button1.Height + 10)
form.Controls.AddRange([| button1; label1 |] )

let async1(syncContext, form : System.Windows.Forms.Form) =
    async {
        let label1 = form.Controls.[1]
        // Do something. 
        do! Async.Sleep(10000)
        let threadName = System.Threading.Thread.CurrentThread.Name
        let threadNumber = System.Threading.Thread.CurrentThread.ManagedThreadId
        label1.Text <- label1.Text + sprintf "Something [%s] [%d]" threadName threadNumber

        // Switch to the UI thread and update the UI. 
        do! Async.SwitchToContext(syncContext)
        let threadName = System.Threading.Thread.CurrentThread.Name
        let threadNumber = System.Threading.Thread.CurrentThread.ManagedThreadId
        label1.Text <- label1.Text + sprintf "Here [%s] [%d]" threadName threadNumber

        // Switch back to the thread pool. 
        do! Async.SwitchToThreadPool()
        // Do something. 
        do! Async.Sleep(10000)
        let threadName = System.Threading.Thread.CurrentThread.Name
        let threadNumber = System.Threading.Thread.CurrentThread.ManagedThreadId
        label1.Text <- label1.Text +
                       sprintf "Switched to thread pool [%s] [%d]" threadName threadNumber
    }

let buttonClick(sender:obj, args) =
    let button = sender :?> Button
    Async.Start(async1(syncContext, button.Parent :?> Form))
    let threadName = System.Threading.Thread.CurrentThread.Name
    let threadNumber = System.Threading.Thread.CurrentThread.ManagedThreadId
    button.Parent.Text <- sprintf "Started asynchronous workflow [%s] [%d]" threadName threadNumber
    ()

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

플랫폼

Windows 8, Windows 7, Windows Server 2012, Windows Server 2008 R2

버전 정보

F# Core 라이브러리 버전

2.0, 4.0, 노트북 지원

참고 항목

참조

Control.Async 클래스(F#)

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