2017-01-01 62 views
1

我正在玩這個MSDN頁面的一些圖表示例,但似乎應用程序會彈出一個圖表窗口,然後在渲染實際圖表之前立即退出。這裏是我試圖運行標題爲「在後臺檢索數據」的示例。程序在運行邏輯之前退出

open System 
open System.Threading 
open System.Drawing 
open System.Windows.Forms 
open FSharp.Charting 
open System.Windows.Forms.DataVisualization.Charting 

/// Add data series of the specified chart type to a chart 
let addSeries typ (chart : Chart) = 
    let series = new Series(ChartType = typ) 
    chart.Series.Add(series) 
    series 

/// Create form with chart and add the first chart series 
let createChart typ = 
    let chart = new Chart(Dock = DockStyle.Fill, Palette = ChartColorPalette.Pastel) 
    let mainForm = new Form(Visible = true, Width = 700, Height = 500) 
    let area = new ChartArea() 
    area.AxisX.MajorGrid.LineColor <- Color.LightGray 
    area.AxisY.MajorGrid.LineColor <- Color.LightGray 
    mainForm.Controls.Add(chart) 
    chart.ChartAreas.Add(area) 
    chart, addSeries typ chart 

let chart, series = createChart SeriesChartType.FastLine 
let axisX = chart.ChartAreas.[0].AxisX 
let axisY = chart.ChartAreas.[0].AxisY 

chart.ChartAreas.[0].InnerPlotPosition <- new ElementPosition(10.0f, 2.0f, 85.0f, 90.0f) 

let updateRanges (n) = 
    let values = 
     seq { 
      for p in series.Points -> p.YValues.[0] 
     } 
    axisX.Minimum <- float n - 500.0 
    axisX.Maximum <- float n 
    axisY.Minimum <- values |> Seq.min |> Math.Floor 
    axisY.Maximum <- values |> Seq.max |> Math.Ceiling 

let ctx = SynchronizationContext.Current 

let updateChart (valueX, valueY) = 
    async { 
     do! Async.SwitchToContext(ctx) 
     if chart.IsDisposed then 
      do! Async.SwitchToThreadPool() 
      return false 
     else 
      series.Points.AddXY(valueX, valueY) |> ignore 
      while series.Points.Count > 500 do 
       series.Points.RemoveAt(0) 
      updateRanges (valueX) 
      do! Async.SwitchToThreadPool() 
      return true 
    } 

let randomWalk = 
    let rnd = new Random() 

    let rec loop (count, value) = 
     async { 
      let count, value = count + 1, value + (rnd.NextDouble() - 0.5) 
      Thread.Sleep(20) 
      let! running = updateChart (float count, value) 
      if running then return! loop (count, value) 
     } 
    loop (0, 0.0) 

Async.Start(randomWalk) 

回答

2

Async.Start操作開始在後臺異步工作流,然後只要後臺工作被添加到隊列完成。如果你的程序在此之後完成,那麼後臺工作永遠不會運行。

如果您使用的是Windows窗體編寫應用程序,那麼你可能需要的東西,如:

Async.Start(randomWalk) 
Application.Run(mainForm) 

Start通話將安排工作和Run通話將控制傳遞給Windows窗體來運行應用程序,直到mainForm關閉了。

在其他上下文中,您可以以不同的方式處理 - 在腳本中,您的代碼可以工作,因爲F#Interactive在執行命令後繼續運行後臺工作。在控制檯應用程序中,您可以運行Console.ReadLine並讓用戶通過在任意點按Enter鍵來終止應用程序。

相關問題