473,320 Members | 1,900 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Threading problem

I need some help to understand a specific threading problem :
I wrote a function "BrowserObjects()" for testing webcontent.

....
IHTMLDocument3 currentDoc = (IHTMLDocument3)ObjectFromLResult(lRes, ref
IID_IHTMLDocument,0);
IHTMLElementCollection frameCol = currentDoc.getElementsByTagName("FRAME");
foreach (IHTMLElement element in frameCol)
{
if (element is IHTMLElement)
{
DispHTMLFrameElement frameElement = (DispHTMLFrameElement)element;
IHTMLWindow2 newWindow = frameElement.contentWindow;
//InvalidCastException, if called in separate thread?
....
}
}
....

no problem, except when I try the following :

Thread secThread = new Thread(new ThreadStart(RunWebTest);
secThread.Start();

public void RunWebTest()
{
...
BrowserObjects();
...
}

as soon as I call the function in a separate thread, it raises a
"InvalidCastException : Schnittstelle wird nicht unterstützt." (german VS
..NET, would be Interface not supported/implemented I guess)

Could someone explain me why this Exception is only raised when I called in
a new thread?
And if it's a general interface/threading problem, why does it never happen
on IHTMLDocument3 ?
Only the call the IHTMLWindow2 raises the exception.

thx :)

Ulf

Nov 16 '05 #1
4 5685
Ulf,

Seems you are trying to to use a COM object created on one thread in
another. It is not allowed to pass COM interfaces between threads - they
should be marshaled instead.
In the unmanaged world, this is done through CoMarshalInterfaceToThread. Not
sure if .NET handles this automatically behind the scenes, so this might be
the case.

Try to create the HTMLDocument instance from scratch on your worker thread.
Also, try to mark your Main method as [MTAThread]

--
Sincerely,
Dmitriy Lapshin [C# / .NET MVP]
Bring the power of unit testing to the VS .NET IDE today!
http://www.x-unity.net/teststudio.aspx

"Ulf Bietz" <ul*@nospam.com> wrote in message
news:cb**********@ngspool-d02.news.aol.com...
I need some help to understand a specific threading problem :
I wrote a function "BrowserObjects()" for testing webcontent.

...
IHTMLDocument3 currentDoc = (IHTMLDocument3)ObjectFromLResult(lRes, ref
IID_IHTMLDocument,0);
IHTMLElementCollection frameCol = currentDoc.getElementsByTagName("FRAME"); foreach (IHTMLElement element in frameCol)
{
if (element is IHTMLElement)
{
DispHTMLFrameElement frameElement = (DispHTMLFrameElement)element;
IHTMLWindow2 newWindow = frameElement.contentWindow;
//InvalidCastException, if called in separate thread?
....
}
}
...

no problem, except when I try the following :

Thread secThread = new Thread(new ThreadStart(RunWebTest);
secThread.Start();

public void RunWebTest()
{
...
BrowserObjects();
...
}

as soon as I call the function in a separate thread, it raises a
"InvalidCastException : Schnittstelle wird nicht unterstützt." (german VS
.NET, would be Interface not supported/implemented I guess)

Could someone explain me why this Exception is only raised when I called in a new thread?
And if it's a general interface/threading problem, why does it never happen on IHTMLDocument3 ?
Only the call the IHTMLWindow2 raises the exception.

thx :)

Ulf


Nov 16 '05 #2
Hi Dmitriy,

thx for your suggestions. I tried MTAThread already, but with no success.
From my understanding, I create and use the COM object in the same thread.
Here is the code :

private void Form1_Load(object sender, System.EventArgs e)
{
Thread secThread = new Thread(new ThreadStart(StartTest));
secThread.Priority = ThreadPriority.Lowest;
secThread.CurrentCulture = new CultureInfo("en-GB",false);
secThread.Start();

//if I run directly
// StartTest() ;
// everything works fine
}

public void StartTest()
{
const int SMTO_ABORTIFHUNG = 0x00000002;

WarObj w = new WarObj(); //library for automated tests

Process proc = new Process();
proc.StartInfo.FileName = "iexplore";
proc.StartInfo.Arguments = "any website";
proc.Start();

int lMsg, lRes = 0, hWnd;

Guid IID_IHTMLDocument = new Guid("626FC520-A41E-11CF-A731-00A0C9082637");

hWnd = w.GetHandle(1,"Internet Explorer_Server");
if (hWnd == 0)
{
MessageBox.Show("Could not find Internet Explorer_Server");
return;
}

lMsg = Win32.RegisterWindowMessage("WM_HTML_GETOBJECT");
Win32.SendMessageTimeout(hWnd,lMsg,0,0,SMTO_ABORTI FHUNG,1000, ref lRes);
if(lRes == 0)
{
MessageBox.Show("Could not send WM_HTML_GETOBJECT message");
return;
}
IHTMLDocument3 myInstance =
(IHTMLDocument3)Win32.ObjectFromLresult(lRes,ref IID_IHTMLDocument,0);
IHTMLElementCollection elements = myInstance.getElementsByTagName("FRAME");

foreach(IHTMLElement element in elements )
{
if(element is IHTMLFrameElement)
{
DispHTMLFrameElement frameElement = (DispHTMLFrameElement)element;
IHTMLWindow2 window = frameElement.contentWindow;
IHTMLDocument2 frameDoc = window.document;
IHTMLElementCollection allTag = frameDoc.all;
foreach(IHTMLElement myTag in allTag)
{
if ((myTag.tagName.Equals("INPUT") || myTag.tagName.Equals("A"))&&
myTag.outerHTML.IndexOf("login")>=0)
{
MessageBox.Show("Login found");
}
}
}
}
proc.Kill();
}

Any hints where I'm wrong ?

thx :)

Ulf

"Dmitriy Lapshin [C# / .NET MVP]" <x-****@no-spam-please.hotpop.com> schrieb
im Newsbeitrag news:uW**************@TK2MSFTNGP09.phx.gbl...
Ulf,

Seems you are trying to to use a COM object created on one thread in
another. It is not allowed to pass COM interfaces between threads - they
should be marshaled instead.
In the unmanaged world, this is done through CoMarshalInterfaceToThread. Not sure if .NET handles this automatically behind the scenes, so this might be the case.

Try to create the HTMLDocument instance from scratch on your worker thread. Also, try to mark your Main method as [MTAThread]

--
Sincerely,
Dmitriy Lapshin [C# / .NET MVP]
Bring the power of unit testing to the VS .NET IDE today!
http://www.x-unity.net/teststudio.aspx

Nov 16 '05 #3
Hi again,
I simply added the ApartmentState :

private void Form1_Load(object sender, System.EventArgs e)
{
Thread secThread = new Thread(new ThreadStart(StartTest));
secThread.Priority = ThreadPriority.Lowest;
secThread.CurrentCulture = new CultureInfo("en-GB",false);
secThread.ApartmentState = ApartmentState.STA;
secThread.Start();
}

works fine now, but I'll still have to spend some hours compulsing MSDN to
understand why :)

Ulf
Nov 16 '05 #4
Ulf,

I am really glad you've resolved the issue. The explanation seems to be as
follows:

Any thread talking to COM should register with the COM subsystem by calling
CoInitialize(). When you start an unmanaged thread and plan to use COM from
it, one of the first calls in the thread routine should be a call to
CoInitialize(). For a .NET Thread, you instruct it to register with COM by
setting its ApartmentState property.

--
Sincerely,
Dmitriy Lapshin [C# / .NET MVP]
Bring the power of unit testing to the VS .NET IDE today!
http://www.x-unity.net/teststudio.aspx

"Ulf Bietz" <ul*@nospam.com> wrote in message
news:cb**********@ngspool-d02.news.aol.com...
Hi again,
I simply added the ApartmentState :

private void Form1_Load(object sender, System.EventArgs e)
{
Thread secThread = new Thread(new ThreadStart(StartTest));
secThread.Priority = ThreadPriority.Lowest;
secThread.CurrentCulture = new CultureInfo("en-GB",false);
secThread.ApartmentState = ApartmentState.STA;
secThread.Start();
}

works fine now, but I'll still have to spend some hours compulsing MSDN to
understand why :)

Ulf


Nov 16 '05 #5

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

Similar topics

65
by: Anthony_Barker | last post by:
I have been reading a book about the evolution of the Basic programming language. The author states that Basic - particularly Microsoft's version is full of compromises which crept in along the...
19
by: Jane Austine | last post by:
As far as I know python's threading module models after Java's. However, I can't find something equivalent to Java's interrupt and isInterrupted methods, along with InterruptedException....
17
by: Andrae Muys | last post by:
Found myself needing serialised access to a shared generator from multiple threads. Came up with the following def serialise(gen): lock = threading.Lock() while 1: lock.acquire() try: next...
2
by: Egor Bolonev | last post by:
hi all my program terminates with error i dont know why it tells 'TypeError: run() takes exactly 1 argument (10 given)' =program==================== import os, os.path, threading, sys def...
77
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...
11
by: Paul Sijben | last post by:
I am stumped by the following problem. I have a large multi-threaded server accepting communications on one UDP port (chosen for its supposed speed). I have been profiling the code and found...
17
by: OlafMeding | last post by:
Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. ...
9
by: cgwalters | last post by:
Hi, I've recently been working on an application which does quite a bit of searching through large data structures and string matching, and I was thinking that it would help to put some of this...
5
by: CCLeasing | last post by:
For an application I'm creating I want to create a 'fake' progress bar. By fake I mean a progress bar that looks like it's doing something but actually isn't. I know philosophically this isn't...
126
by: Dann Corbit | last post by:
Rather than create a new way of doing things: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2497.html why not just pick up ACE into the existing standard:...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Shćllîpôpď 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

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.