SAP Knowledge Base Article - Public

1583132 - Error "ThreadStateException was unhandled" occours when running Crystal Reports in a multithreaded .NET application

Symptom

Running a Crystal Reports ReportDocument object or a RAS ReportClientDocument object in a multithreaded .NET application will generate one or both of the following exceptions:

  • ThreadStateException was unhandled
  • Current thread must be set to single thread apartment (STA) mode before OLE calls can be made. Ensure that your Main function has STAThreadAttribute marked on it. This exception is only raised if a debugger is attached to the process.

Environment

  • Windows OS all versions
  • Visual Studio all versions
  • Crystal Reports XI R2
  • Crystal Reports 2008
  • Crystal Reports for Visual Studio 2010

Reproducing the Issue

In Visual Studio create a child thread that instatiates a ReportDocument or ReportClientDocument object

Cause

  • The ReportDocument and ReportClientDocument are marked safe for single threaded apartment model only.
  • The ReportDocument and ReportClientDocument can only be safely accessed by the thread that created it, or the parent thread.

Resolution

 The apartment state property of the thread needs to be set to single threaded apartment (STA) for example:

 Thread MyCrystalThread = new Thread(new ThreadStart(RunReport));
 MyCrystalThread.SetApartmentState(ApartmentState.STA);
 MyCrystalThread.Start();

Keywords

Multi-Threaded CR RAS error 13 hangs desktop CR for VS CRforVS thread multithreading , KBA , BI-DEV-NET , BI Software Development Kits (SDKs) - .NET or Other , How To

Product

Crystal Reports 2008 V1 ; SAP Crystal Reports 2011 ; SAP Crystal Reports 2011, feature pack 03 ; SAP Crystal Reports XI ; SAP Crystal Reports XI R2 ; SAP Crystal Reports, developer version for Microsoft Visual Studio ; SAP Crystal Reports, version for Visual Studio .NET 2005 ; SAP Crystal Reports, version for Visual Studio .NET 2008 ; SAP Crystal Reports, version for Visual Studio .NET 9.1