-1

I have a method "ImportExcel" that is called in a new thread:

[STAThread]
    private void btnImportExcel_Click(object sender, EventArgs e)
    {
        // Start by setting up a new thread using the delegate ThreadStart
        // We tell it the entry function (the function to call first in the thread)
        // Think of it as main() for the new thread.
        ThreadStart theprogress = new ThreadStart(ImportExcel);

        // Now the thread which we create using the delegate
        Thread startprogress = new Thread(theprogress);
        startprogress.SetApartmentState(ApartmentState.STA);

        // We can give it a name (optional)
        startprogress.Name = "Book Detail Scrapper";

        // Start the execution
        startprogress.Start();            
    }

Now within ImportExcel() function, there is a try catch block. In the catch block, if a particular exception occurs, I wish to call ImportExcel() function again. How do I do that?

Samar Rizvi
  • 423
  • 5
  • 18
  • Do you need to call that function directly or in a new thread.And what is the reason for calling the same method inside the catch block? – Prasanna Aarthi Aug 18 '14 at 09:52
  • In the catch block, I check for internet connectivity issue, I ask the user if internet connection is resolved, if yes, then ImportExcel() function is again called. I used invoke method for this, the function starts working, but the application ui becomes unresponding. – Samar Rizvi Aug 18 '14 at 09:56
  • I would suggest to check for internet connection before calling this function and not in the catch block.. – Prasanna Aarthi Aug 18 '14 at 09:59

1 Answers1

2

Probably you could just add one more level of indirection to handle such issue:

private void TryMultimpleImportExcel()
{
    Boolean canTryAgain = true;

    while( canTryAgain)
    {
        try
        {
            ImportExcel();
            canTryAgain = false;
        }
        catch(NotCriticalTryAgainException exc)
        {
            Logger.Log(exc);
        }
        catch(Exception critExc)
        {
            canTryAgain = false;
        }
    }
}


    // ...
    ThreadStart theprogress = new ThreadStart(TryMultimpleImportExcel);
    // ..
    startprogress.Start();    

ALSO:

If you want to allow your user to stop the possibly endless processing, you may want to use CancellationToken, as it is described here - How to use the CancellationToken property?. Thanks @MikeOfSST.

Community
  • 1
  • 1
Eugene Podskal
  • 10,270
  • 5
  • 31
  • 53
  • 1
    Adding a `CancellationToken` and providing the user with a way to break the loop would be nice. Then you can make the function that starts the thread `async` and `await` the operation completing. – Evil Dog Pie Aug 18 '14 at 10:04