473,826 Members | 3,039 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

P/Invoke, [STAThread()] and multi threading

igd
I am forced to decorate my .NET Main()-method with [STAThread()], since
an unmanaged function (which i am calling through P/Invoke) calls
CoCreateInstanc e() in turn. The problem is, that another unmanaged
function starts a new thread which invokes a callback function. This
callback function is a delegate in my .NET app and since it is executed
in a STA (Singe Threaded Appartment), the callback function/delegate
can not called right. Is there a possibility to fix this dilemma?

Thanks in advance!

- igd -

Jan 23 '07 #1
4 4236
"igd" <ki********@gma il.comwrote in message
news:11******** **************@ l53g2000cwa.goo glegroups.com.. .
>I am forced to decorate my .NET Main()-method with [STAThread()], since
an unmanaged function (which i am calling through P/Invoke) calls
CoCreateInstanc e() in turn. The problem is, that another unmanaged
function starts a new thread which invokes a callback function. This
callback function is a delegate in my .NET app and since it is executed
in a STA (Singe Threaded Appartment), the callback function/delegate
can not called right. Is there a possibility to fix this dilemma?

Thanks in advance!

- igd -

STA threads and native callbacks are not related unless you are talking about COM callbacks,
what exactly is not working as you expect?

Willy.

Jan 23 '07 #2
igd
The unmanaged server wrappes a COM server, i.e. when I call the
unmanaged function ASIOStart() through P/Invoke it calls IASIO::start()
in turn, which is a method of a COM interface. The IASIO::start()
method creates a new thread. This new thread calls the callback
function (a delegate in my .NET client).

The callback function prototypes:

void bufferSwitch(lo ng index, ASIOBool processNow);
ASIOTime *bufferSwitchTi meInfo(ASIOTime *timeInfo, long index, ASIOBool
processNow);

The COM server after all invokes unmanaged callbacks (?).

Summary:

(1) Encapsulated COM client starts new thread with CreateThread()
(2) new thread calls unmanaged callback function
(3) callback function is actually a delegate in STA .NET client

When the new thread try to call the callback function the following
message appears:

"An unhandled win32 exception occured in Test.vshost.exe [2252]"

On 23 Jan., 22:34, "Willy Denoyette [MVP]" <willy.denoye.. .@telenet.be>
wrote:
STA threads and native callbacks are not related unless you are talking about COM callbacks,
what exactly is not working as you expect?

Willy.
Jan 24 '07 #3
"igd" <ki********@gma il.comwrote in message
news:11******** **************@ k78g2000cwa.goo glegroups.com.. .
The unmanaged server wrappes a COM server, i.e. when I call the
unmanaged function ASIOStart() through P/Invoke it calls IASIO::start()
in turn, which is a method of a COM interface. The IASIO::start()
method creates a new thread. This new thread calls the callback
function (a delegate in my .NET client).

The callback function prototypes:

void bufferSwitch(lo ng index, ASIOBool processNow);
long in C# is 64 bit! This should be an int.

ASIOTime *bufferSwitchTi meInfo(ASIOTime *timeInfo, long index, ASIOBool
processNow);

The COM server after all invokes unmanaged callbacks (?).
COM callbacks are called on interfaces (ConnectionPoin t) passed to them by the client, IMO
this is not what you are doing here.
Note that as I said in another thread of yours, that the Encapsulated C native dll is the
COM client here, I'm having the impression that you are incorrectly mixing both interop
models, IMO you should call the COM object from C# directly, that is, your C# code should be
the client.

Summary:

(1) Encapsulated COM client starts new thread with CreateThread()
As said in another thread, it's up to the client to initialize the threads apartment, which
he fails to do, that's why you had to set the STAThread attribute on Main.
Question is what's the thread is used for?
Is the COM instance (CoCreateInstan ce) created on this thread?
How is this thread initialized? STA or other or none?
What kind of COM object is this, STA or other, regular COM server or ActiveX server?
(2) new thread calls unmanaged callback function
What kind of callback, native or COM?
(3) callback function is actually a delegate in STA .NET client
Good if the callback is a simple native callback, wrong if it's a COM callback.
Willy.

Jan 24 '07 #4
igd
void bufferSwitch(lo ng index, long processNow);
long in C# is 64 bit! This should be an int.
Yes i know. This was the prototype declared in the native client. I map
this callback function to the following .net delegate:

[UnmanagedFuncti onPointer(Calli ngConvention.Cd ecl)]
public delegate void BufferSwitchCal lback(int doubleBufferInd ex, int
directProcess);

But that is not the point. Concrete:

There is a unmanaged function which expect a pointer to a structure
containig four callback function pointers (class with four delegates in
..net). Two of that callback function are called from the same thread
and >IT WORKS<. The other two callbacks are called from the new thread
the COM server created and do NOT work. the callback prototypes are
defined in the NATIVE client, NOT in the COM server. the native client
give that struct pointer direct to the COM server:

ASIOError ASIOCreateBuffe rs(ASIOBufferIn fo *bufferInfos, long
numChannels,
long bufferSize, ASIOCallbacks *callbacks) // native function
{
// ...
return theAsioDriver->createBuffers( bufferInfos, numChannels,
bufferSize, callbacks); // COM interface
}

The COM server then use this structure this way:

this->callbacks = callbacks;
callbacks->bufferSwitchCa llback (...); // just use NATIVE callbacks

Unfortunately I MUST NOT use the COM server direct and MUST go through
the unmanaged wrapper.

Jan 24 '07 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2726
by: sonu | last post by:
Hi I have developed a smart client application. When i try to execute it. It displays the first form which is the login screen. On giving the corrent login id and password, the main form opens. It has 2 menus. On clicking the submenu, it throws an STAThread exception. The error details are given below. I have included System.Threading.Thread.CurrentThread.ApartmentState =
77
5396
by: Jon Skeet [C# MVP] | last post by:
Please excuse the cross-post - I'm pretty sure I've had interest in the article on all the groups this is posted to. I've finally managed to finish my article on multi-threading - at least for the moment. I'd be *very* grateful if people with any interest in multi-threading would read it (even just bits of it - it's somewhat long to go through the whole thing!) to check for accuracy, effectiveness of examples, etc. Feel free to mail...
6
31870
by: Peter Rilling | last post by:
Okay, I have the main thread which does all the work. This main thread spawns a worker thread that just periodically poles the environment looking for a certain condition. This second thread is very small, and only is responsible for raising a flag when the environment changes. What I want is for the main thread to raise an event when the change has been flagged. I other words, I want the main thread to raise the event, not this small...
0
2965
by: Pawan Narula via DotNetMonster.com | last post by:
hi all, i'm using VB.NET and trying to code for contact management in a tree. all my contacts r saved in a text file and my C dll reads them one by one and sends to VB callback in a sync mode thread. so far so good. all contacts r added properly. now when another login adds me in his contact, i recv a subscription, so i popup a form and ask for accept/reject. this all happens in a separate thread. popup form gets opened and choice is...
7
2133
by: Jeff Stewart | last post by:
I need a thread to run a subroutine which updates my main form's progress bar. I've properly marshaled all UI updates to the main UI thread, and after the main thread starts the worker thread, it waits for the worker thread to complete by means of a while t.isAlive, sleep(0) mechanism. But when my worker thread calls my UpdateProgressBar routine, which calls Me.Invoke, the invoke call blocks forever. But I can't figure out why the main...
6
2823
by: k.mellor | last post by:
Hi, I hope someone can help. I have written a simple form to demonstrate my problem/question. The code follows. The form starts a thread, which using delegates updates a label (Every second adds another dot to the label). This works great. However, when I put the GUI thread to sleep (Thread.Sleep), the thread seems to stall. At first I was expecting dots to still appear, but obviously as the GUI thread is asleep, they will not. ...
4
19476
by: garyusenet | last post by:
I am at a loss with this. I tried to go back to basics, and start learning all i didn't understand, starting at the top of the code file generated by VS. But I can't seem to get any sort of start on this problem, anything I read on the NET goes too far above my head to be of any use. For instance typical explanations say things like... 'The STAThreadAttribute marks a thread to use the Single-Threaded COM Apartment if COM is needed'
0
1881
ammoos
by: ammoos | last post by:
hi friends pls help me.. i got an assignment which i feel very difficult to me.. i dont have more knowledge about multi-threading in .net... the assignment details is below.... pls help me... i have to submit this assignment today evening... please....... Windows Application to demonstrate the use of Multi-Threading with Synchronous & Asynchronous Threading. Requirements 1) A form with a) a button to initialize threads ...
12
5067
by: rafalK | last post by:
Hi All, I have a big problem with STAThread attribute. I'm using XNA framework connected with WinForms. XNA is working in non STAThread. I have a problem with displaying CommonDialog forms e.g. OpenFileDialog. I can't declare a main method as STAThread because of XNA framework. Is there any way to declare form or some method in form as STAThread (I think that a method from Form can invoke OpenFileDialog) maybe I'm wrong. Do you know...
0
9631
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10740
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10464
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10182
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9288
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6934
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5767
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3943
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3065
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.