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

C# 调用已在新线程中调用的方法,c#,multithreading,single-threaded,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

我有一个在新线程中调用的方法“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()函数。如何做到这一点?

也许您可以再添加一个间接级别来处理此类问题:

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,如本文所述-。谢谢@mikeofst。

您需要直接调用该函数还是在新线程中调用该函数。在catch块中调用相同方法的原因是什么?在catch块中,我检查internet连接问题,我询问用户internet连接是否已解决,如果是,则再次调用ImportExcel()函数。我为此使用了invoke方法,函数开始工作,但应用程序ui变得不响应。我建议在调用此函数之前检查internet连接,而不是在catch块中。添加
CancellationToken
并为用户提供中断循环的方法会很好。然后,您可以使启动线程的函数
async
等待操作完成。