✅ System threading tasks

I am trying to accomplish a checker to make sure a task/function doesn't take to long to run. If it does it must end. Basically kill the task. This is the code I have:

c#
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
CancellationToken cancellationToken = cancellationTokenSource.Token;

System.Threading.Tasks.Task task = System.Threading.Tasks.Task.Run(() => UpdateQueryBox(), cancellationToken);

System.Threading.Tasks.Task delayTask = System.Threading.Tasks.Task.Delay(5000);

System.Threading.Tasks.Task.WaitAny(task, delayTask);

if (!task.IsCompleted)
{
    cancellationTokenSource.Cancel();
    MessageBox.Show("The server is not responding, please re-try.", "Error");

}


But with this it is creating cross threading. I had this issue before but with accessing data, and I did this to solve it:
c#
private string GetControlText(Control control)
{
    if (control.InvokeRequired)
    {
        // Call the method recursively in the UI thread
        return (string)control.Invoke(new Func<string>(() => control.Text));
    }
    else
    {
        return control.Text;
    }
}


This worked, but now the panel (error on picture) that is trying to be accessed is to update it...I update a lot of the information on the form so the same workaround cannot be done. Please lemme know if you need more information.
Capture.PNG
Was this page helpful?