Solved

Multiple Threads in C#

Posted on 2008-06-10
6
1,949 Views
Last Modified: 2013-11-07
I am working on a class library that uses methods to create new threads that fire events when they are completed. Here's how it works.
1. Application calls method ResizeImageAsync(inputFile, outputFile, width, height);
2. The ResizeImageAsync() creates a new thread that runs in low priority with the IsBackground property = true.
3. The thread resizes the image and writes it to a folder based on the outputFile parameter.
3. The thread calls an event called OnResize(outputFile). The outputFile parameter is the value of the ResizeImageAsync() outputFile parameter.

The problem I am having is the ResizeImageAsync() method will be called multiple times at once. When I call it more than 30 times the computer hangs. I think it's because I am creating too many threads at once.
I haven't done very much multi-threading yet for an application so I'm not sure of which System.Threading class I should use to pool the threads so they are managed properly. I could just be disposing of the threads improperly as well.

I've attached some of the code in the application.
public event ResizeCompletedDelegate OnResize;
 

        public void ResizeImageMaxAsync(string imagePath, string outputPath, int maxWidth, int maxHeight)

        {

            Thread thread = new Thread(delegate()

                                           {

                                               this.ResizeImageMax(imagePath, outputPath, maxWidth, maxHeight);
 

                                               // Fire the completed event

                                               this.InvokeOnResize(outputPath);

                                           });

            thread.Priority = ThreadPriority.Lowest;

            thread.IsBackground = true;

            thread.Start();

        }
 

        private void InvokeOnResize(string filePath)

        {

            ResizeCompletedDelegate resizeDelegate = this.OnResize;

            if (resizeDelegate != null)

            {

                resizeDelegate(filePath);

            }

        }
 
 

// Application Usage Section.
 

// This is the event that will fire. It just writes out the path to the location of the resized image.

editor.OnResize += delegate(string outputFile)

        {

            Console.WriteLine("File: {0} Completed Resize", outputFile);

        };
 

// This is just an example of looping through multiple instances of the ResizeImageAbsoluteAsync method. It returns immediatelly after the thread is created and not when the thread has finished.

for (int i = 0; i < 60; i++)

{

    editor.ResizeImageAbsoluteAsync(imagePath, String.Format(outputPath, Guid.NewGuid().ToString()), 250, 250);

}

Open in new window

0
Comment
Question by:DuNuNuBatman
  • 4
  • 2
6 Comments
 
LVL 12

Accepted Solution

by:
jandromeda earned 500 total points
ID: 21752373
Use the ThreadPool to spawn new threads.
0
 

Author Comment

by:DuNuNuBatman
ID: 21752383
Also, is there a way I can limit the number of threads executed at one time. Ideally, it should be based on the number of cores the machine has because I don't want to be resizing 20 images at once. I want them to start returning as soon as possible.
0
 
LVL 12

Expert Comment

by:jandromeda
ID: 21752409
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 12

Expert Comment

by:jandromeda
ID: 21752440
You can limit the number of threads using the SetMaxThreads() method of the ThreadPool class.
0
 

Author Comment

by:DuNuNuBatman
ID: 21752792
It doesn't look like I can set the thread priority using the ThreadPool class. Do you think creating a thread in the thread pool would be an issue?
I've been running it and it seems to be working correctly, but I don't know if that could cause problems.
Thread thread = new Thread(delegate()

                                                        {

                                                            this.ResizeImageMax(imagePath, outputPath, maxWidth, maxHeight);
 

                                                            // Fire the completed event

                                                            this.InvokeOnResize(outputPath);

                                                        });

Open in new window

0
 
LVL 12

Expert Comment

by:jandromeda
ID: 21752998
Well as far as I know you cannot set the thread priority when you are using ThreadPool but this class provides an efficient thread management functionality. If you use the approach you are using right now you will have to limit the number of threads created at a particular instance of time. But this functionality is already built into ThreadPool and since it is a framework class I think it is trouble free.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Problem with SqlConnection 5 115
asp.net bundle 8 36
Trouble with References... 5 22
Create XML 5 33
Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/A_4334-Minify-and-Concatenate-Your-Scripts-and-Stylesheets.html)…
This article describes relatively difficult and non-obvious issues that are likely to arise when creating COM class in Visual Studio and deploying it by professional MSI-authoring tools. It is assumed that the reader is already familiar with the cla…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now