Search Results for

    Show / Hide Table of Contents

    RequiresThread

    RequiresThreadAttribute is used to indicate that a test method, class, or assembly should always run on a separate thread. Optionally, the desired apartment state for the thread may be specified.

    Constructors

    RequiresThreadAttribute()
    RequiresThreadAttribute(ApartmentState apartment)
    
    Parameter Type Description
    apartment ApartmentState The apartment state for the thread. Must be STA or MTA (not Unknown).

    Applies To

    Test Methods Test Fixtures (Classes) Assembly
    ✅ ✅ ✅

    Examples

    Fixture Level

    [TestFixture]
    [RequiresThread]
    public class FixtureOnSeparateThread
    {
        [Test]
        public void TestRunsOnSeparateThread()
        {
            // All tests in this fixture run on a dedicated thread
            Assert.That(Thread.CurrentThread.IsThreadPoolThread, Is.False);
        }
    }
    

    Method Level with Apartment State

    [TestFixture]
    public class MixedThreadTests
    {
        [Test]
        [RequiresThread]
        public void TestOnSeparateThread()
        {
            // This test runs on a separate thread
            Assert.Pass();
        }
    
        [Test]
        [RequiresThread(ApartmentState.STA)]
        public void TestOnSTAThread()
        {
            // This test runs on a separate STA thread
            Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.STA));
        }
    
        [Test]
        [RequiresThread(ApartmentState.MTA)]
        public void TestOnMTAThread()
        {
            // This test runs on a separate MTA thread
            Assert.That(Thread.CurrentThread.GetApartmentState(), Is.EqualTo(ApartmentState.MTA));
        }
    }
    

    Assembly Level

    // All tests in this assembly will run on separate threads
    [assembly: RequiresThread]
    

    Notes

    1. This attribute always creates a new thread, regardless of the current thread's apartment state.
    2. To create a thread only when the current apartment state is not appropriate, use the [Apartment] attribute instead.
    3. When used without an ApartmentState argument, the thread uses the default apartment state (MTA).
    4. This attribute is useful for tests that modify thread-local state or require isolation from other tests.

    See Also

    • Apartment Attribute
    • SingleThreaded Attribute
    • Edit this page
    In this article
    Back to top Generated by DocFX | Copyright (c) 2018- The NUnit Project - Licensed under CC BY-NC-SA 4.0