JP..t
JP..t

Reputation: 615

Don't execute the thread when Thread is already running

I have a Thread to export date into Excel.

But when i run the Thread for the second time it may not execute..

My code:

 if (Thread.CurrentThread == null || Thread.CurrentThread.ThreadState == System.Threading.ThreadState.Stopped)
 {
     new Thread(() =>
     {
         Thread.CurrentThread.Name = "Export to Excel Thread";
         Thread.CurrentThread.IsBackground = true;

         //Code to export to Excel
         // ...
     }).Start();
  }
  else
  {
      MessageBox.Show("Please wait untill the current export is done");
  }

I think the problem is that the Thread is not the currentThread in the if statement.

How to solve this?

Upvotes: 0

Views: 325

Answers (3)

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174309

I would go with the TPL.

You could use something like this:

// in your class
private Task _exportTask;

// in your method
if(_exportTask == null || _exportTask.IsCompleted || _exportTask.IsCanceled || _exportTask.IsFaulted)
{
    _exportTask = Task.Factory.StartNew(() => /* Code to export to Excel */);
}
else
{
    MessageBox.Show("Please wait until the current export is done");
}

Explanation why your code doesn't work:
The current thread can never be null, because that would mean that there is no thread to execute the code that performs this check. Likewise, it can't be stopped, because that again would mean that the code of your check wouldn't be executed, as the thread is stopped.
Thread.CurrentThread always returns the thread that is executing the code that is accessing the value of Thread.CurrentThread.

Upvotes: 3

Sinatr
Sinatr

Reputation: 21999

When the first Thread is running(Creating a Excel) The Thread may not execute again. Until the Thread is done and the 'export' button is clicked again!

This could be done really simple by disabling button.

private void button1_Click(object sender, EventArgs e)
{
    button1.Enabled = false;
    Task.Run(() =>
    {
        // ... do something here

        Invoke((Action)(() => button1.Enabled = true)); // enable button again
    });
}

If export can be called from multiple places (button, menu, automation, scheduler, etc.), then see other answers.

Upvotes: 0

cyberj0g
cyberj0g

Reputation: 3787

I think you should use BackgroundWorker class that will handle threading stuff for you. On the second export button click just check IsBusy property and do nothing if it's true. Good luck.

Upvotes: 2

Related Questions