UI only partly responsive while running tasks and updating ui
i have the following ui -
For each line connection to crm should be tested. This is done in separate thread.
The test status of the connection to crm system is then updated in last column.
The problem is that the ui is only partly reponsive during threads run and updating of the ui, i.e. i would like to click through the lines whilst updating.
Here is my code:
private async void btnTestAllConnections_Click(object sender, EventArgs e)
{
await TestConnectionsAsync();
}
private async Task TestConnectionsAsync()
{
try
{
int idxConn = columnLookup[ColumnIndex.Connection].Index;
if (lvInitParameters.Items.Count == 0)
return;
ManagedConnection connection = null;
btnTestAllConnections.Visible = false;
btnTestConnection.Visible = false;
panel2.Enabled = false;
panel3.Enabled = false;
tableLayoutPanel1.Enabled = false;
btnCancelTest.Visible = true;
List<Task> tasks = new List<Task>();
var cts = new CancellationTokenSource();
CancellationToken token = cts.Token;
foreach (ListViewItem lvi in lvInitParameters.Items)
{
InitParamProxy currentProfile = (InitParamProxy)lvi.Tag;
lvi.SubItems[idxConn].Text = "Testing...";
Task<bool> result =null;
try
{
result = Task.Run(
() =>
{
try
{
connection = currentProfile.ManagedConnection;
return connection?.ConnectionSuccess ?? false;
}
catch (Exception ex)
{
// crm exception
return false;
}
}, token);
if (token.IsCancellationRequested)
{
Console.WriteLine("\nCancellation requested in continuation...\n");
token.ThrowIfCancellationRequested();
}
ListViewItem testItem =
items.Where(si => ((InitParamProxy)lvi.Tag).ProfileKey.Equals(((InitParamProxy)si.Tag).ProfileKey)).SingleOrDefault();
lvi.SubItems[idxConn].Text = (result.Result) ? "Success" : "Fail";
if (testItem != null)
testItem.SubItems[idxConn].Text = (result.Result) ? "Success" : "Fail";
}
catch
{
ListViewItem testItem =
items.Where(si => ((InitParamProxy)lvi.Tag).ProfileKey.Equals(((InitParamProxy)si.Tag).ProfileKey)).SingleOrDefault();
lvi.SubItems[idxConn].Text = "Canceled";
if (testItem != null)
testItem.SubItems[idxConn].Text = "Canceled";
}
tasks.Add(result);
}
Task.WaitAll(tasks.ToArray());
btnTestAllConnections.Visible = true;
btnTestConnection.Visible = true;
panel2.Enabled = true;
panel3.Enabled = true;
tableLayoutPanel1.Enabled = true;
btnCancelTest.Visible = false;
}
catch (Exception)
{
}
}
In the end of your method you have
Task.WaitAll(tasks.ToArray());
This will block until all tasks are done. You should instead use WhenAll
await Task.WhenAll(tasks.ToArray());
You are also using result.Result
in several places, and this also blocks. This should be replaced by awaiting the task, i.e. await result