473,568 Members | 2,939 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

C#, Thread Problem

8 New Member
Hi guys, need you advice here. Have to say I’m new to Threading applications and C# in general, so may be it is really simple and just I can not see it.

I created a really simple project to show my problem (VS 2008 C# WinForm Project)
I have a 3rd party COM object which I want to run when click on a Start button. The ApartmentState of this COM object is MTA and since WinForm Thread is STA only,
I have to create a new Thread to be able to work with my COM, so here is the code.

Expand|Select|Wrap|Line Numbers
  1. Program.cs
  2.   public delegate void ThreadStart();
  3.         [STAThread]
  4.         static void Main()
  5.         {
  6.             Application.EnableVisualStyles();
  7.             Application.SetCompatibleTextRenderingDefault(false);
  8.             Application.Run(new frmCOMNameRIC());
  9.  
  10.         }
  11.  
  12. Form1.cs
  13.  
  14.        public partial class frmCOMNameRIC : Form
  15.         {
  16.         public double tm=0.0; 
  17.  
  18.  
  19.         public frmCOMNameRIC()
  20.         {
  21.             InitializeComponent();
  22.         }
  23.  
  24.         private void cmdStart_Click(object sender, EventArgs e)
  25.         {
  26.             Thread t = new Thread(new ThreadStart(UseCOMNameThread));
  27.             t.SetApartmentState(ApartmentState.MTA);
  28.             t.Start(); //Start thread t
  29.             t.Join();  //Wait until thread t finishes
  30.             lblTime.Text=tm.ToString();
  31.         }
  32.  
  33.  
  34.         public void UseCOMNameThread(){
  35.  
  36.             DateTime current;
  37.             MyCOMObject lst = new MyCOMObject();
  38.  
  39.             try
  40.             {
  41.                 //do the job
  42.                 tm=Convert.ToDouble(result);
  43.             }
  44.             catch(Exception ex)
  45.             {
  46.                 //log error message
  47.             }
  48.           System.Runtime.InteropServices.Marshal.ReleaseComObject(lst)
  49. }
  50.  
  51. private void cmdExit_Click(object sender, EventArgs e){
  52.          this.Close();
  53.         }    
Everything working fine and label showing the expected result, but clicking Exit killing the application:

"The memory could not be read. Click OK to terminate the program.

I think it might be a problem with thread management but I do not know exactly what is wrong.

I’m out of ideas, really appreciate your help.
Oct 30 '09 #1
8 2161
tlhintoq
3,525 Recognized Expert Specialist
TIP: When you are writing your question, there is a button on the tool bar that wraps the [code] tags around your copy/pasted code. It helps a bunch. Its the button with a '#' on it. More on tags. They're cool. Check'em out.
Oct 30 '09 #2
tlhintoq
3,525 Recognized Expert Specialist
Creating the thread inside the _Click handler means you don't have a convenient reference to it in the future. You might try creating the thread as a program-wide object, but setting it on the click event. That way you can reference it to call a thread.abort against later when your application is closing.

Expand|Select|Wrap|Line Numbers
  1.  
  2.             Thread t); // Now has a scope of the entire program
  3.  
  4.         private void cmdStart_Click(object sender, EventArgs e)
  5.         {
  6.             t = new Thread(new ThreadStart(UseCOMNameThread)
  7.             t.SetApartmentState(ApartmentState.MTA);
  8.             t.Start(); //Start thread t
  9.             t.Join();  //Wait until thread t finishes
  10.             lblTime.Text=tm.ToString();
  11.         }
  12.  
  13.         private void Form1_Closing(object sender, EventArgs e)
  14.         {
  15.              t.abort();  // Abort the thread before the application closes.
  16.         }
  17.  
  18.  
Oct 30 '09 #3
ilyaw77
8 New Member
Hi tlhintoq, thnx for the good tips.
I tried to make thread t "global" as per your advice but it still give me the same application error on Exit click. Also question, Join() method should exit the thread when it finish its execution, do I need the Abort() method as well in the Exit click procedure?

Thank you for reply,
Ilya
Oct 30 '09 #4
tlhintoq
3,525 Recognized Expert Specialist
I tried to make thread t "global" as per your advice but it still give me the same application error on Exit click.
I never expected that just changing the scope of the thread would fix the issue. The only reason to do that is to be able to reference from outside of the method that created it, so you could call the abort function.

do I need the Abort() method as well in the Exit click procedure?
It costs nothing to try it and see if it works. This would be the "trial" part of "trial and error", which is something you can expect to do a LOT in any type of programming.
Oct 30 '09 #5
ilyaw77
8 New Member
Hi everybody, I still very much appreciate if someone could give me any hint on this problem.

Ilya
Nov 2 '09 #6
tlhintoq
3,525 Recognized Expert Specialist
Did you try the thread.abort() as suggested?
Nov 2 '09 #7
ilyaw77
8 New Member
Yes tlhintoq I did, same problem as before.
Nov 2 '09 #8
tlhintoq
3,525 Recognized Expert Specialist
I'm out of ideas. Sorry
Nov 3 '09 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

6
2317
by: Tony Proctor | last post by:
Hi everyone We're experiencing some serious anomalies with the scheduling of ASP threads. I'd be interested to hear if anyone knows what algorithm is used (e.g. simple round-robin, or something more sophisticated), and what situations might perturb it. Even a hint as to what would be considered normal scheduling might help. The root of...
7
2691
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates that. Problem is that when program is started many threads are created (see output section), when only two should be running at any time. Can you...
20
2998
by: Doug Thews | last post by:
I ran into an interesting re-pain delay after calling the Abort() method on a thread, but it only happens the very first time I call it. Every time afterward, there is no delay. I've got a delegate inside the UI that I call to update the progress meter. I use the Suspend() and Abort() methods based on button events. I can watch the...
6
23718
by: Tomaz Koritnik | last post by:
I have a class that runs one of it's method in another thread. I use Thread object to do this and inside ThreadMethod I have an infinite loop: While (true) { // do something Thread.Sleep(100); } The problem is that I don't know how to terminate the thread when my class
13
5062
by: Bob Day | last post by:
Using vs2003, vb.net I start a thread, giving it a name before start. Code snippet: 'give each thread a unique name (for later identification) Trunk_Thread.Name = "Trunk_0_Thread" ' allow only 1 thread per line Trunk_Thread.ApartmentState = ApartmentState.STA
4
2543
by: fred | last post by:
I use a Synclock in a secondary thread and also stop the thread using the abort method. If the abort occurs while the thread is in the Synclock will the SyncLock always be released before the thread stops or do I need to add some extra code to avoid Synclock staying on after the thread has been stopped. Thanks Fred
51
54795
by: Hans | last post by:
Hi all, Is there a way that the program that created and started a thread also stops it. (My usage is a time-out). E.g. thread = threading.Thread(target=Loop.testLoop) thread.start() # This thread is expected to finish within a second
14
6858
by: joey.powell | last post by:
I am using VS2005 for a windows forms application. I need to be able to use a worker thread function to offload some processing from the UI thread. The worker thread will need access to a datagridview on the form. I am using the following code to spawn the worker thread... Thread WorkerThread = new Thread(new ThreadStart(WT_MyFunction));...
7
5890
by: Sin Jeong-hun | last post by:
Hi. I'm writing a Client/Multi-threaded Server program on Windows Vista. It worked fine on Windows Vista, but when the server ran on Windows XP, I/O operation has been aborted because of either a thread exit or an application request exception randomly occurred at the OnReceive method (asynchronous tcp stream reading). I searched all...
34
2762
by: Creativ | last post by:
Why does Thread class not support IDisposable? It's creating quite some problem. Namely, it can exhaust the resource and you have not control over it.
0
7693
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7604
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...
0
7916
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. ...
0
8117
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...
0
6275
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...
1
5498
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
1
2101
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1207
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
932
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...

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.