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

前端 未结 8 1399
刺人心
刺人心 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:26

    Like the others, I'm not sure that's such a good idea, but if you really want to do it, then you can create a subclass of SynchronizationContext that allows posting and sending delegates to the target thread (if it's a WinForms thread the work is done for you as such a subclass already exists). The target thread will have to implement some sort of a message pump equivalent though, to receive the delegates.

    0 讨论(0)
  • 2020-12-16 02:26

    @Orion Edwards

    I take your point about an exception being thrown in the finally block.

    However, I think there is a way - using yet another thread - of using this exception-as-interrupt idea.

    Thread A:

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

    Thread B:

    try {
        Signal thread C that exceptions may be thrown
        //do stuff, without needing to check exit conditions
        Signal thread C that exceptions may no longer be thrown
    }
    catch {
        // exception/interrupt occurred handle...
    }
    finally {
        // ...and clean up
        CloseResourceOne();
        CloseResourceTwo();
    }
    

    Thread C:

     while(thread-B-wants-exceptions) {
            try {
                Thread.Sleep(1) 
            }
            catch {
                // exception was thrown...
                if Thread B still wants to handle exceptions
                    throw-in-B
            }
        }
    

    Or is that just silly?

    0 讨论(0)
提交回复
热议问题