0

I am searching a library to generate and export a chart as on a Net Core 3.1 BackgroundService. I found Live-Charts.

In this i found a link to an example to export the chart to image. But this is for WPF and did not work. Had this exception in the line var myChart = new LiveCharts.Wpf.CartesianChart:

System.InvalidOperationException: 'The calling thread must be STA, because many UI components require this.'

This the my BackgroundService code:

public class Worker1 : BackgroundService
{
    private readonly ILogger<Worker1> _logger;

    public Worker1(ILogger<Worker1> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            BuildPngOnClick();
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            await Task.Delay(10000, stoppingToken);
        }
    }


    private void BuildPngOnClick()
    {
        var myChart = new LiveCharts.Wpf.CartesianChart
        {
            DisableAnimations = true,
            Width = 600,
            Height = 200,
            Series = new SeriesCollection
            {
                new LineSeries
                {
                    Values = new ChartValues<double> {1, 6, 7, 2, 9, 3, 6, 5}
                }
            }
        };

        var viewbox = new Viewbox();
        viewbox.Child = myChart;
        viewbox.Measure(myChart.RenderSize);
        viewbox.Arrange(new Rect(new Point(0, 0), myChart.RenderSize));
        myChart.Update(true, true); //force chart redraw
        viewbox.UpdateLayout();

        SaveToPng(myChart, @"c:\chart.png");
    }

    private void SaveToPng(FrameworkElement visual, string fileName)
    {
        var encoder = new PngBitmapEncoder();
        EncodeVisual(visual, fileName, encoder);
    }

    private static void EncodeVisual(FrameworkElement visual, string fileName, BitmapEncoder encoder)
    {
        var bitmap = new RenderTargetBitmap((int)visual.ActualWidth, (int)visual.ActualHeight, 96, 96, PixelFormats.Pbgra32);
        bitmap.Render(visual);
        var frame = BitmapFrame.Create(bitmap);
        encoder.Frames.Add(frame);
        using (var stream = File.Create(fileName)) encoder.Save(stream);
    }
}

Is it possible to export a chart using Live-Charts in a Net Core 3.1 BackgroundService? If no, do you know another free library that support multiple axes where it is possible?

Thanks in advance.

bruno.almeida
  • 2,746
  • 1
  • 24
  • 32
  • 1) as for first question - you [can try to start](https://stackoverflow.com/a/11681802/2501279) STA thread yourself though I would say you should not 2) as for second - this question doesn’t meet a SO guideline - seeking recommendations tools, software libraries. – Guru Stron Jun 05 '20 at 11:27
  • @GuruStron, what are the disadvantages of creating a STA thread? – bruno.almeida Jun 05 '20 at 13:59

0 Answers0