I have a .NET 4.0 Windows Service that hosts components. Our project lead says that when calling methods on certain components, that performance is slow. He suspects that it may be an STA component that incurs this performance penalty.
To test this theory, I have been asked to create a STA component with one method accepts an integer and returns the integer multiplied by two. This component will be hosted in the service and tests will be run.
Can something like this be created in C# or would it be necessary to create it in C++?
If possible, could you include some code?
EDIT: (code based on Han's suggestion)
using System.Runtime.InteropServices;
namespace STADemo
{
[ComVisible(true)]
public class STAClass
{
public int Calculate(int value)
{
return 2*value;
}
}
}
Windows Service uses MTA threading model. You haven't specified the exact model of the COM components suspected to be causing a slowdown. If they are marked as 'Apartment'
or ''
(blank) in their ThreadingModel
registry entries, that may indeed hurt the performance, because all calls will be marshaled from the Windows Service's current thread to a dedicated thread created by COM to host the components.
If you really need to prove that, you can create an Single-threaded or Apartment-threaded component in C# by providing a custom registration method with [ComRegisterFunction]
. Here's an example of using ComRegisterFunction
to mark a component as Apartment
.
Note, there's still a subtle difference between Single-threaded and Apartment-threaded components in how the class factory object handles threading, as described in this article. Single-threaded components are really rare, your components most likely are Apartment-threaded, but make sure to check their registry keys anyway.