The calling thread cannot access this object even after adding Dispatcher.Invoke

zeero :

The calling thread cannot access this object because a different thread owns it even after adding Dispatcher.Invoke.

The problem is still intact even after adding Dispatcher.Invoke.

async Task capturePredict()
{
    await Dispatcher.Invoke( async () =>
    {
        PngBitmapEncoder image = new PngBitmapEncoder();
        image.Frames.Add(BitmapFrame.Create(bitmap));

        using (Stream stream = File.Create(@"E:\ImageClassificationTraining\image.png"))
        {
            await Task.Run(() => image.Save(stream));
        }
    });
}
Clemens :

In contrast to decoding a BitmapSource (which can be frozen to make it cross-thread accessible), encoding can seemingly not be done in a thread other than the UI thread.

You may however separate the encoding step from writing the file, by something like this:

public async Task SaveImageAsync(BitmapSource bitmap, string path)
{
    var encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(bitmap));

    using (var memoryStream = new MemoryStream())
    {
        encoder.Save(memoryStream);
        memoryStream.Position = 0;

        using (var fileStream = File.Create(path))
        {
            await memoryStream.CopyToAsync(fileStream);
        }
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=376850&siteId=1