调用已在新线程中调用的方法

时间:2014-08-18 09:49:30

标签: c# multithreading single-threaded

我有一个在新线程中调用的方法“ImportExcel”:

[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();            
    }

现在在ImportExcel()函数中,有一个try catch块。在catch块中,如果发生特定异常,我希望再次调用ImportExcel()函数。我该怎么做?

1 个答案:

答案 0 :(得分:2)

可能你可以再添加一个间接级别来处理这个问题:

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

同时

如果您希望允许用户停止可能无休止的处理,您可能需要使用CancellationToken,如此处所述 - How to use the CancellationToken property?。谢谢@MikeOfSST。