In a C# WinForms app, I am trying to move an image dithering operation into a background thread and add a progress bar to the form, to show the state of the processing. I have achieved all of that so far, but I have no clue how to get the resulting bytes back in the main thread.
Old Code:
interface ImageConverter {
MCBlockVariant[,] Convert(Bitmap image, Size size, ImageDitherer ditherer);
}
private void btnConvert_Click(object sender, EventArgs e) {
ImageDitherer d = null;
if (cbDithering.Checked) {
d = (ImageDitherer)cmbDitherers.SelectedValue;
d.Reset(scaledSize);
}
//TODO: P1 show progress bar somewhere
MCBlockVariant[,] blocks = imageConverter.Convert(image, scaledSize, d);
MCPACResultForm form = new MCPACResultForm(blocks, palette);
form.Show();
}
I was able to successfully get this process to run in the background, by changing the the method signatures and invoking the progress bar on the main form thread, to update it throughout the process. That all works flawlessly. I just have no idea how to raise the results of that process, back to the main form thread, so I can feed the result into the new output form.
New Code:
interface ImageConverter {
Task<MCBlockVariant[,]> Convert(Bitmap image, Size size, ImageDitherer ditherer, ProgressBar progress);
}
private async void btnConvert_ClickAsync(object sender, EventArgs e) {
ImageDitherer d = null;
if (cbDithering.Checked) {
d = (ImageDitherer)cmbDitherers.SelectedValue;
d.Reset(scaledSize);
}
Task<MCBlockVariant[,]> blocks = Task.FromResult(new MCBlockVariant[0, 0]);
await Task.Run(() => {
blocks = imageConverter.Convert(image, scaledSize, d, progressBarConvertImage);
});
// NOTE: This no longer works because `await` doesn't actually wait.
// MCPACResultForm form = new MCPACResultForm(blocks.Result, palette);
// form.Show();
}