When I run the code after the form is initialized, it works the way I intended. But, when I load it for the first time in the form Load event it lags the UI from drawing for a second. I don’t really want to make a splash screen as there’s already some UI elements that indicate work is being done.
volatile bool ABfired = false;
public form_Main()
{
InitializeComponent();
}
void GetSearchableDataCache()
{
this.UIThread(() =>
{
ultraActivityIndicator1.AnimationEnabled = true;
ultraLabel_Status.Text = "Querying SQL...";
});
var projids = new List<string>();
var names = new List<string>();
ABfired = false;
Thread A = (new Thread(() =>
{
while (!ABfired)
{
}
projids = new sql.ProjectIDs(true).Get();
})
{
Name = "Thread A", IsBackground = true
});
Thread B = (new Thread(() =>
{
while (!ABfired)
{
}
names = new sql.names(true).Get();
})
{
Name = "Thread B", IsBackground = true
});
Thread AB = (new Thread(() =>
{
ABfired = true;
while (A.IsAlive || B.IsAlive)
{
}
this.UIThread(() =>
{
ultraActivityIndicator1.AnimationEnabled = false;
ultraLabel_Status.Text = "Ready";
});
})
{
Name = "Thread AB", IsBackground = true
});
A.Start();
B.Start();
AB.Start();
}
private void form_Main_Load(object sender, EventArgs e)
{
GetSearchableDataCache();
}
Your threads are spinning, so they each use up an entire CPU core.
That slows the system down dramatically.
You should never wait using a
whileloop like you’re doing now.Instead, wait on a
ManualResetEvent.However, you can replace all of that code with much a simpler implementation using
Tasks and no explicit threads.Using
Task.ContinueWithwill allow you to run a task after the previous one finishes without wasting a thread.