© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
19 replies
XE SparkyCracked

✅ 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:

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");

}
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:
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;
    }
}
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ Installing System.Threading.Tasks.Dataflow in Unity
C#CC# / help
3y ago
Cannot implicitly convert type 'System.Threading.Tasks.Task<string>' to 'string'
C#CC# / help
3y ago
✅ THREADING & CHARTS
C#CC# / help
12mo ago
VS threading
C#CC# / help
2y ago