2017-01-01 31 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键来终止应用程序。

相关问题