1

I read many solution over here and other places but never got it right. I kinda feel embarrassed just by asking this but here I'm...

My code:

private void btnStart_Click(object sender, EventArgs e)
        {
                MyClass SomeData = new MyClass()
                Thread ProcessThread = new Thread(c => StartService(SomeData));
                ProcessThread.Start();
        }

private void StartService(MyClass someData)
        {
            try
            {
                //System.Exception throws in this Execute method
                someData.Execute();
            }
            catch(Exception Ex)
            {
                Show(Ex);
//Informing me some exception occurred.
            }
        }

When an exception is thrown in Excute method (which, currently I'm throwing it deliberately to test), I CANNOT abort or end the thread and start ANOTHER to run SAME method. So, basically if I would like to END that thread and then RE-RUN it again. If you think re-running is risky, I will put up a question that waits a human confirmation whether to re-run or end it. Anyways, I cannot even END it and the thread stays doing nothing at Thread ProcessThread = new Thread(c => StartService(SomeData)); line.

Could you please help me?

4

2 回答 2

2

呼吁

Show(Ex);

似乎暗示了一个 UI 动作。如果这是真的,并且 Show() 没有正确编组该 UI 操作,则可能会引发未处理的异常。

除了观察之外,您的线程应该在 Show() 退出后自行结束,因为之后线程的方法中没有更多的语句。您无需执行任何操作(也不应该)手动结束线程。除非在相当不寻常的情况下,最好让线程自己结束(有时通过向它们发送结束信号,或者在这种情况下,只是让方法运行完成)。

在你的catch块中,你当然可以启动一个新线程

Thread ProcessThread = new Thread(c => StartService(SomeData));

请注意,这ProcessThread与您的代码中的范围不同,因为它们都是在方法中定义的。如果您希望能够在您的类中访问该变量,也许将其提升为类方法。

于 2013-01-28T20:26:34.987 回答
0

完成Thread后将自动退出。StartService你不需要做任何事情来“结束”它。

如果您想开始一个新线程,您可以直接在您的方法中执行此操作:

    private void StartService(MyClass someData)
    {
        try
        {
            //System.Exception throws in this Execute method
            someData.Execute();
        }
        catch(Exception Ex)
        {
            Show(Ex);
            // "Restart" this thread
            (new Thread(c => StartService(SomeData))).Start();
        }
    }

但是,您可能需要考虑加入一些逻辑来防止线程不断地重新启动自己。一种选择是保留它重新启动次数的计数器,如果它重新启动超过几次,则在记录后优雅地退出。这将防止立即引发的异常只是不断地抽入和抽出线程......

于 2013-01-28T20:26:27.373 回答