<p>The code that I want to write is like this:</p>

<pre><code>void MethodOnThreadA()
{
    for (;;)
    {
        // Do stuff
        if (ErrorConditionMet)
            ThrowOnThread(threadB, new MyException(...));
    }
}

void MethodOnThreadB()
{
    try
    {
        for (;;)
        {
            // Do stuff
        }
    }
    catch (MyException ex)
    {
        // Do the right thing for this exception.
    }
}
</code></pre>

<p>I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated.  Is there a better mechanism that I can use?</p>

<p>Here is a more fleshed out example of periodically checking:</p>

<pre><code>Dictionary&lt;Thread, Exception&gt; exceptionDictionary = new Dictionary&lt;Thread, Exception&gt;();

void ThrowOnThread(Thread thread, Exception ex)
{
    // the exception passed in is going to be handed off to another thread,
    // so it needs to be thread safe.
    lock (exceptionDictionary)
    {
        exceptionDictionary[thread] = ex;
    }
}

void ExceptionCheck()
{
    lock (exceptionDictionary)
    {
        Exception ex;
        if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex))
            throw ex;
    }
}

void MethodOnThreadA()
{
    for (;;)
    {
        // Do stuff
        if (ErrorConditionMet)
            ThrowOnThread(threadB, new MyException(...));
    }
}

void MethodOnThreadB()
{
    try
    {
        for (;;)
        {
            // Do stuff
            ExceptionCheck();
        }
    }
    catch (MyException ex)
    {
        // Do the right thing for this exception.
    }
}
</code></pre>

[{'answer_id': 44661, 'author': 'Lasse V. Karlsen', 'author_id': 267, 'author_profile': 'https://Stackoverflow.com/users/267', 'pm_score': 3, 'selected': False, 'text': "<p>There are enough problems with exceptions that can be thrown on threads by other mechanisms, like aborting threads and the likes, that you should find another way of doing it.</p>\n\n<p>An exception is a mechanism used to signal that a process has experienced something exceptional that it cannot deal with. You should try to avoid writing the code so that an exception is used to signal that <em>something else</em> has experienced something exceptional.</p>\n\n<p>That other thread will most likely not know how to handle the exception <em>in all cases where it could be thrown by your code</em>.</p>\n\n<p>In short, you should find some other mechanism for aborting your threads than using exceptions.</p>\n\n<p>Use event objects or similar to tell a thread to abort its processing, that's the best way.</p>\n"}, {'answer_id': 44671, 'author': 'Eric Z Beard', 'author_id': 1219, 'author_profile': 'https://Stackoverflow.com/users/1219', 'pm_score': 0, 'selected': False, 'text': "<p>I'm interested to know why you would want to do this.  There's not an easy way to do it, because it's not a good practice.  You should probably go back to your design and figure out a cleaner way to accomplish the end goal.</p>\n"}, {'answer_id': 44673, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 0, 'selected': False, 'text': "<p>I don't think that's a good idea.. \nTake another crack at this problem - Try using some other mechanism like shared data to  signal between threads.</p>\n"}, {'answer_id': 44719, 'author': 'On Freund', 'author_id': 2150, 'author_profile': 'https://Stackoverflow.com/users/2150', 'pm_score': 0, 'selected': False, 'text': "<p>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.</p>\n"}, {'answer_id': 44761, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 4, 'selected': True, 'text': '<p>This is NOT a good idea</p>\n\n<p><a href="http://blog.headius.com/2008/02/rubys-threadraise-threadkill-timeoutrb.html" rel="noreferrer">This article talks about ruby\'s timeout library.</a> which throws exceptions across threads.</p>\n\n<p>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.</p>\n\n<p>In a nutshell, what can (and does) happen is this:</p>\n\n<p>ThreadA: </p>\n\n<pre><code>At some random time, throw an exception on thread B:\n</code></pre>\n\n<p>ThreadB:</p>\n\n<pre><code>try {\n    //do stuff\n} finally {\n    CloseResourceOne();\n    // ThreadA\'s exception gets thrown NOW, in the middle \n    // of our finally block and resource two NEVER gets closed.\n    // Obviously this is BAD, and the only way to stop is to NOT throw\n    // exceptions across threads\n    CloseResourceTwo();\n}\n</code></pre>\n\n<p>Your \'periodic checking\' example is fine, as you\'re not actually throwing exceptions across threads.<br>\nYou\'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.<br>\nHowever, 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.</p>\n'}, {'answer_id': 44852, 'author': 'Rob', 'author_id': 1006, 'author_profile': 'https://Stackoverflow.com/users/1006', 'pm_score': 0, 'selected': False, 'text': '<p>@Orion Edwards</p>\n\n<p>I take your point about an exception being thrown in the finally block.</p>\n\n<p>However, I think there is a way - using yet another thread - of using this exception-as-interrupt idea.</p>\n\n<p>Thread A:</p>\n\n<pre><code>At some random time, throw an exception on thread C:\n</code></pre>\n\n<p>Thread B:</p>\n\n<pre><code>try {\n    Signal thread C that exceptions may be thrown\n    //do stuff, without needing to check exit conditions\n    Signal thread C that exceptions may no longer be thrown\n}\ncatch {\n    // exception/interrupt occurred handle...\n}\nfinally {\n    // ...and clean up\n    CloseResourceOne();\n    CloseResourceTwo();\n}\n</code></pre>\n\n<p>Thread C:</p>\n\n<pre><code> while(thread-B-wants-exceptions) {\n        try {\n            Thread.Sleep(1) \n        }\n        catch {\n            // exception was thrown...\n            if Thread B still wants to handle exceptions\n                throw-in-B\n        }\n    }\n</code></pre>\n\n<p>Or is that just silly?</p>\n'}, {'answer_id': 47154, 'author': 'Eric', 'author_id': 4540, 'author_profile': 'https://Stackoverflow.com/users/4540', 'pm_score': 1, 'selected': False, 'text': '<p>While researching another issue, I came across this article which reminded me of your question:</p>\n\n<p><a href="http://www.ondotnet.com/pub/a/dotnet/2003/02/18/threadabort.html" rel="nofollow noreferrer">Plumbing the Depths of the ThreadAbortException using Rotor</a></p>\n\n<p>It shows the gyrations that .NET goes through to implement Thread.Abort() -- presumably any other cross-thread exception would have to be similar.  (Yeech!)</p>\n'}, {'answer_id': 3436002, 'author': 'GenericProgrammer', 'author_id': 178196, 'author_profile': 'https://Stackoverflow.com/users/178196', 'pm_score': 2, 'selected': False, 'text': '<p>What Orion Edwards is saying is not entirely true: is not the "only" way.</p>\n\n<blockquote>\n<pre><code>// Obviously this is BAD, and the only way to stop is to NOT throw\n// exceptions across threads\n</code></pre>\n</blockquote>\n\n<p>Using CER (<strong>Constrained Execution Regions</strong>) in C# allows you to release your resources as an atomic operation, protecting your code from inter-thread exceptions. This technique is used by several classes of the .NET Framework which work with Windows\' native API, where an unreleased handle may cause a memory leak.</p>\n\n<p>See <a href="http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.prepareconstrainedregions.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.runtimehelpers.prepareconstrainedregions.aspx</a></p>\n\n<p>The following example shows how to reliably set handles by using the <code>PrepareConstrainedRegions</code> method. To reliably set a handle to a specified pre-existing handle, you must ensure that the allocation of the native handle and the subsequent recording of that handle within a <code>SafeHandle</code> object is atomic. Any failure between these operations (such as a thread abort or out-of-memory exception) will result in the native handle being leaked. You can use the <code>PrepareConstrainedRegions</code> method to make sure that the handle is not leaked.</p>\n\n<p>As simple as:</p>\n\n<pre><code>public MySafeHandle AllocateHandle()\n{\n    // Allocate SafeHandle first to avoid failure later.\n    MySafeHandle sh = new MySafeHandle();\n\n    RuntimeHelpers.PrepareConstrainedRegions();\n    try { }\n    finally  // this finally block is atomic an uninterruptible by inter-thread exceptions\n    {\n        MyStruct myStruct = new MyStruct();\n        NativeAllocateHandle(ref myStruct);\n        sh.SetHandle(myStruct.m_outputHandle);\n    }\n\n    return sh;\n}\n</code></pre>\n'}]
['https://Stackoverflow.com/questions/44656', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4592/']