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