Search code examples
c#multithreadingsingle-threaded

Call a method that has already been called in a new thread


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?


Solution

  • 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.