更新: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 为空,则该异步计算与 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
请参见
参考
Microsoft.FSharp.Control 命名空间 (F#)
修订记录
| Date | 修订记录 | 原因 | 
|---|---|---|
| 2010 年 7 月 | 添加了代码示例。 | 信息补充。 |