There are few ways we can prevent C# App from freezing
Task.Factory.StartNew(() => longRunningTask(qrCodeAsSvg));
void longRunningTask(string qrCodeAsSvg)
{
Thread.Sleep(2000);
File.WriteAllText(@"D:QRCodeMyTest.svg", qrCodeAsSvg);
}
However, using the above method you won’t be able change the property of any element (e.g Button)
Task.Factory.StartNew(() => (btn_QR_Generate.Content = "Saving.."));
Here is another option in which I’m using async method
//Else statement
else
{
SvgQRCode qrCode = new SvgQRCode(qrCodeData);
qrCodeAsSvg = qrCode.GetGraphic(20);
//string path = @"D:\QRCode\MyTest.svg";
//File.WriteAllText(path, qrCodeAsSvg);
//MessageBox.Show("");
//Calling async method
SaveFile(qrCodeAsSvg);
}
}
//global variable
string qrCodeAsSvg;
//async method
private async void SaveFile(string qrCodeAsSvg)
{
var btn = QR_Generate.Content;
QR_Generate.Content = "Saving...";
await Task.Run(() => longRunningTask(qrCodeAsSvg));
QR_Generate.Content = btn;
}
//Long running task wich is will responsible for freezing UI Or Main Task
void longRunningTask(string qrCodeAsSvg)
{
Thread.Sleep(2000);
File.WriteAllText(@"D:\QRCode\MyTest.svg", qrCodeAsSvg);
}