I'm new to C# and I'm trying to use async and await function in C# to work with threading and non blocking GUI.
This is what I have so far:
public async Task ReadInfo()
{
string serial;
android.UpdateDeviceList();
if (android.HasConnectedDevices)
{
serial = android.ConnectedDevices[0];
device = android.GetConnectedDevice(serial);
string model = device.BuildProp.GetProp("ro.product.model");
string bootloader = device.BuildProp.GetProp("ro.bootloader");
string pda = device.BuildProp.GetProp("ro.build.PDA");
addlog("Model : " , Color.White, true, true);
addlog(model, Color.DodgerBlue, true, false);
addlog("Bootloader : ", Color.White, true, true);
addlog(bootloader, Color.DodgerBlue, true, false);
addlog("PDA Version : ", Color.White, true, true);
addlog(pda, Color.DodgerBlue, true, false);
}
else
{
addlog("ADB device not found.", Color.Red, true, true);
}
}
This is the AddLog Method:
public void addlog(string s, Color color, bool isBold, bool newline = false)
{
if (newline)
{
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.AppendText("\r\n")));
}
Color selectionColor = color;
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionStart = rtbLog.Text.Length));
rtbLog.BeginInvoke(new MethodInvoker(() => selectionColor = rtbLog.SelectionColor));
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionColor = color));
if (isBold)
{
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionFont = new Font(rtbLog.Font, FontStyle.Bold)));
}
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.AppendText(s)));
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionColor = selectionColor));
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.SelectionFont = new Font(rtbLog.Font, FontStyle.Regular)));
rtbLog.BeginInvoke(new MethodInvoker(() => rtbLog.ScrollToCaret()));
}
On Button1_Click I have this:
private async void Button1_Click(object sender, EventArgs e)
{
await ReadInfo();
}
I don't know why its freezing the GUI.
Solution to the problem
Changing
public async Task ReadInfo()
to
public void ReadInfo()
and calling on button1_click as
Task.Run(() => ReadInfo());