A
A
Anton Ivanov2021-01-24 14:26:05
C++ / C#
Anton Ivanov, 2021-01-24 14:26:05

Why might there be a problem with asynchrony in this place?

Here is a code snippet:

private static Image Render(IPeakProvider peakProvider, WaveFormRendererSettings settings)
        {
            if (settings.DecibelScale)
                peakProvider = new DecibelPeakProvider(peakProvider, 48);

            var b = new Bitmap(settings.Width, settings.TopHeight + settings.BottomHeight);
            if (settings.BackgroundColor == Color.Transparent)
            {
                b.MakeTransparent();
            }
            using (var g = Graphics.FromImage(b))
            {
                g.FillRectangle(settings.BackgroundBrush, 0,0,b.Width,b.Height);
                var midPoint = settings.TopHeight;

                int x = 0;
                var currentPeak = peakProvider.GetNextPeak();
                while (x < settings.Width)
                {
                    var nextPeak = peakProvider.GetNextPeak();
                    
                    for (int n = 0; n < settings.PixelsPerPeak; n++)
                    {
                        var lineHeight = settings.TopHeight * currentPeak.Max;
                        g.DrawLine(settings.TopPeakPen, x, midPoint, x, midPoint - lineHeight);
                        lineHeight = settings.BottomHeight * currentPeak.Min;
                        g.DrawLine(settings.BottomPeakPen, x, midPoint, x, midPoint - lineHeight);
                        x++;
                    }
....


After I started calling the Render function asynchronously, via
...
var image = await Task.Run(() =>
{
return waveFormRenderer.Render(filePath, peakProvider, settings);
});
...

the program crashes with the error "Object is used elsewhere" on the line
g.DrawLine(settings.TopPeakPen, x, midPoint, x, midPoint - lineHeight);


I don't really understand how this can be, since the instance of g is created uniquely for each call to the Render function.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question