Solved

ContextSwitchDeadlock was detected.

Posted on 2008-06-26
1
2,050 Views
Last Modified: 2013-11-19
I have written a C# windows app which lets the user select a wmf file(s) and then converts this file to jpg file, scans the image pixel by pixel and then crops the white space around the image, next if the image is over a specified width it resizes the images and then saves it.
For smaller wmf files the app converts, crops, resize, and saves them no problem.
But if I select a bigger wmf files the app converts, crops, resize, and saves some of them and then Visual C# shows the following message:
ContextSwitchDeadlock was detected
Message: The CLR has been unable to transition from COM context 0x540fb0 to COM context 0x541120 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping wait or processing a very long running operation without pumping Windows messages. This situation generally has a negative performance impact and may even lead to the application becoming non responsive or memory usage accumulating continually over time. To avoid this problem, all single threaded apartment (STA) threads should use pumping wait primitives (such as CoWaitForMultipleHandles) and routinely pump messages during long running operations.

If i click OK and Play the app continues and finishs, all images are converted, cropped, resized, and saved.

Related Notes:
1.  When the app is processing the images, the windows form title sometime adds "(Not Responding)".  This disapears when the processing is complete.
2. During the image processing the app changes the text in a label.  But the status label only changes at the begining and end of the sub. The lines to change the status label text in the for loops are not reflected on the form, but i never get an error.

I want to add a ProgressBar to the form, but i want to solve the above issues first.
Any ideas?
private void btnWMFconverter_Click(object sender, EventArgs e)

{

    int imagesConverted = 0;

    int estFooterHeight = 0;

    int imageBorder = 0;

    int maxWidth = 0;

    if (!IsPositiveInteger(txtFooterHeight.Text))

    {

        MessageBox.Show("Estimated Footer Height must be a positive integer.", "Invalid Estimated Footer Height", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

        txtFooterHeight.Focus();

    }

    else

    {

        estFooterHeight = Int32.Parse(txtFooterHeight.Text);

        if (!IsPositiveInteger(txtImageBorder.Text))

        {

            MessageBox.Show("Image Border must be a positive integer.", "Invalid Image Border", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

            txtImageBorder.Focus();

        }

        else

        {

            imageBorder = Int32.Parse(txtImageBorder.Text);

            if (!IsPositiveInteger(txtMaxWidth.Text))

            {

                MessageBox.Show("Max Width must be a positive integer.", "Invalid Max Width", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                txtMaxWidth.Focus();

            }

            else

            {

                maxWidth = Int32.Parse(txtMaxWidth.Text);

                lblStatus.Text = "Starting";

                flgWMF.ShowDialog();

                for (int fileCt = 0; fileCt < flgWMF.FileNames.Count(); fileCt++)

                {

                    try

                    {

                        //Convert Image to .jpg

                        lblStatus.Text = "Converting Image " + fileCt.ToString() + " of " + flgWMF.FileNames.Count().ToString() + "\n";

                        string fileName = flgWMF.FileNames[fileCt];

                        Image i = Image.FromFile(fileName, true);

                        Bitmap b = new Bitmap(i);

                        Graphics g = Graphics.FromImage(b);

                        g.Clear(Color.White);

                        g.DrawImage(i, 0, 0, i.Width, i.Height);

                        //Crop .jpg

                        //based on the lowest and highest x and y positions,+20, where the pixel color

                        //isn't the same as the background color

                        lblStatus.Text = "Cropping Image " + fileCt.ToString() + " of " + flgWMF.FileNames.Count().ToString() + "\n\n";

                        lblStatus.Text += "In order to auto crop the image, it must be scanned pixel by pixel.\n";

                        lblStatus.Text += "Depending on the original height and width this process might take a while.";

                        int lowestx = int.MaxValue;

                        int lowesty = int.MaxValue;

                        int highestx = int.MinValue;

                        int higesty = int.MinValue;

                        Color c;

                        for (int x = 0; x < b.Width; x++)

                        {

                            for (int y = 0; y < b.Height - estFooterHeight; y++)

                            {

                                c = b.GetPixel(x, y);

                                if (c.ToArgb() != Color.White.ToArgb())

                                {

                                    if (x < lowestx)

                                    {

                                        lowestx = x;

                                    }

                                    if (y < lowesty)

                                    {

                                        lowesty = y;

                                    }

                                    if (x > highestx)

                                    {

                                        highestx = x;

                                    }

                                    if (y > higesty)

                                    {

                                        higesty = y;

                                    }

                                }

                            }

                        }

                        lowestx = lowestx - imageBorder;

                        lowesty = lowesty - imageBorder;

                        higesty = higesty + imageBorder;

                        highestx = highestx + imageBorder;

                        Size s = new Size(highestx - lowestx + 1, higesty - lowesty + 1);

                        Rectangle r = new Rectangle(lowestx, lowesty, s.Width, s.Height);

                        Bitmap b1 = b.Clone(r, b.PixelFormat);

                        //Resize .jpg

                        lblStatus.Text = "Resizing Image " + fileCt.ToString() + " of " + flgWMF.FileNames.Count().ToString() + "\n";

                        if (maxWidth < b1.Width)

                        {

                            int width = maxWidth;

                            double h = b1.Height * ((double)width / (double)b1.Width);

                            int height = (int)Math.Round(h);

                            Bitmap b2 = new Bitmap(width, height);

                            Graphics g1 = Graphics.FromImage((Image)b2);

                            g1.DrawImage(b1, 0, 0, width, height);

                            b1 = b2;

                        }

                        //Save .jpg

                        lblStatus.Text = "Saving Image " + fileCt.ToString() + " of " + flgWMF.FileNames.Count().ToString() + "\n";

                        string[] fn = fileName.Split("\\".ToCharArray());

                        fn[fn.Count() - 1] = txtPrefix.Text.Trim() + fn[fn.Count() - 1];

                        fn[fn.Count() - 1]=fn[fn.Count() - 1].Substring(0, fn[fn.Count()-1].LastIndexOf('.')+1)+"jpg" ;

                        StringBuilder sb = new StringBuilder();

                        for (int f = 0; f < fn.Count(); f++)

                        {

                            if (!(f == 0))

                                sb.Append("\\");

                            sb.Append(fn[f]);

                        }

                        string newFileName = sb.ToString();// fileName.Replace(".wmf", ".jpg").Replace(".WMF", ".JPG");

                        b1.Save(newFileName, System.Drawing.Imaging.ImageFormat.Jpeg);

                        imagesConverted++;

                    }

                    catch(Exception ex)

                    {

                        MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                    }

                }

            }

        }

        lblStatus.Text = imagesConverted.ToString() + " images successfully converted, cropped, resized and saved.";

    }

}

Open in new window

0
Comment
Question by:msaltz
1 Comment
 
LVL 1

Accepted Solution

by:
msaltz earned 0 total points
ID: 21877254
I think i solved my problem by adding the line
Application.DoEvents();
After the lines i assign the text of my status label.
0

Featured Post

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

Join & Write a Comment

Keep your audience engaged and get the most out of your next presentation with these quick Prezi tips.
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
In addition to being a great web-based presentation tool, Prezi also makes it easy to save your presentation as a PDF to share with others as well. Learn how in this tutorial. Select the share icon from the top menu in your Prezi editor: Select "D…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

758 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

18 Experts available now in Live!

Get 1:1 Help Now