0

my objective is to interrupt an running operation if it exceeds a certain amount of time (.NET Framework 4.0).

The operation is a method that changes some labels in a form.

After reading the accepted answer here, I tried to adapt it in order to be able to access the labels in a form (because the solution proposed there wouldn't allow me to do that: "Cross-thread operation not valid: Control 'label1' accessed from a thread other than the thread it was created on.").

So I came to this:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            Thread t = new Thread(TestMethod);
            t.Start();
            if (!t.Join(TimeSpan.FromSeconds(2)))
            {
                t.Abort();
                label1.Text = "-";
                label2.Text = "Timed out!";
            }
            else
            {
                label1.Text = y.ToString();
                label2.Text = "Completed!";                    
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }                      
    }

    int y;
    private void TestMethod()
    {
        try
        {
            for (int x = 0; x < 6; x++)
            {
                Thread.Sleep(1000);
                y = x; //Used the global variable "y" here because label1 cannot be directly accessed from this thread.                    
            }
        }
        catch (ThreadAbortException)
        {
            // cleanup code, if needed...
        }            
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }          
    }
}

It seems to work fine.

But I'm wondering: is this is a "correct" way of doing it? Is there something I'm missing? Is there a another better/simpler way (for .NET Framework 4.0)?

Thanks in advance.

AlexC
  • 383
  • 8
  • 17
  • 1
    No this is not a good way to do it. 1. `Thread.Abort()` is a bad way to kill a thread. Ideally you want the thread to stop on it's own. This is done by checking some synchronized `flag`. One thread set's the flag, let's call it `StopProcessing` and the other thread respects the flag and systematically exits from its work.. 2. You don't want to do `Thread.Join` in your event thread. This will cause your GUI to freeze. In your case, you can do the check using a GUI timer, for example. – Vikhram Aug 15 '17 at 14:38
  • 1
    The "modern" way to do this in c# is to employ [Task using Synchronization Context and CancellationToken](https://stackoverflow.com/questions/16916253/how-to-get-a-task-that-uses-synchronizationcontext-and-how-are-synchronizationc). Also check the [MSDN doc](https://msdn.microsoft.com/en-us/library/system.threading.tasks.task(v=vs.110).aspx) for it – Vikhram Aug 15 '17 at 14:42
  • @Vikhram , thank you, I'll read the documentation. – AlexC Aug 17 '17 at 08:52

0 Answers0