Is there a good method in C# for throwing an exception on a given thread

前端 未结 8 1519
刺人心
刺人心 2020-12-16 01:22

The code that I want to write is like this:

void MethodOnThreadA()
{
    for (;;)
    {
        // Do stuff
        if (ErrorConditionMet)
            ThrowO         


        
8条回答
  •  醉话见心
    2020-12-16 02:12

    This is NOT a good idea

    This article talks about ruby's timeout library. which throws exceptions across threads.

    It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads.

    In a nutshell, what can (and does) happen is this:

    ThreadA:

    At some random time, throw an exception on thread B:
    

    ThreadB:

    try {
        //do stuff
    } finally {
        CloseResourceOne();
        // ThreadA's exception gets thrown NOW, in the middle 
        // of our finally block and resource two NEVER gets closed.
        // Obviously this is BAD, and the only way to stop is to NOT throw
        // exceptions across threads
        CloseResourceTwo();
    }
    

    Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads.
    You're just setting a flag which says "throw an exception the next time you look at this flag", which is fine as it doesn't suffer from the "can be thrown in the middle of your catch or finally block" problem.
    However, if you're going to do that, you may as well just be setting an "exitnow" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that.

提交回复
热议问题