ActiveX Control Running on Separate Thread

J

Javier Bertran

Hi all,
I have an ActiveX control developed in Visual C++ 6.0 that I want to use in
a C# project. I want the ActiveX code to run on a separate thread, but can't
seem to get it to work. If for example my ActiveX member has an infinite
loop, the .NET app gives all processing to the ActiveX and never returns,
not even to redraw the window. Here is what I tried (in a nutshell):

VC++ 6.0 OCX code:

void CMyAXControlCtrl::Loop()
{
while(1) {} // infinite loop
}

C# application code:

private void MyThreadTask()
{
axMyAXControl1.Loop(); // calls the ActiveX infinite loop
function
}

private void foo()
{
threadAX = new Thread(new ThreadStart(this.MyThreadTask));
threadAX.Start();
}

Note that my Main function in C# is declared with [STAThread], if I declare
it as [MTAThread] I get an unhandled exception of type
'System.Threading.ThreadStateException' in system.windows.forms.dll (Could
not instantiate ActiveX control because the current thread is not in a
single-threaded apartment.)

Of course if I do not use an AX control and have the equivalent code in my
C# project, the threading works fine (just made sure!!!):

private void MyThreadTask()
{
// axMyAXControl1.Loop(); // calls the ActiveX infinite loop
function
while (true) {}
}

private void foo()
{
threadAX = new Thread(new ThreadStart(this.MyThreadTask));
threadAX.Start();
}

Thanks in advance,

Javier Bertran
 
M

Mohamoss

hi Javier

One thing you can try instantiate an Asynchronous delegate then make it
point to your function , then use its begin invoke and end invoke instead
of creating your own thread .
You can just wrap your ActiveX function in a c# function and then
instantiate the delegate on this function .
Here you are a link to read more about that

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/htm
l/cpovrAsynchronousDelegates.asp
hope this helps

Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC
 
W

Willy Denoyette [MVP]

First, all ActiveX controls need an STA thread to run on, so you need to set
the ApartmentState of the thread to STA before starting the thread.
Second, you need to pump the message loop in your newly created thread,
failing to do so can result in a deadlock.
Third, you should never loop infinitely as this will hog the CPU and disturb
the message pump.

Willy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top