Solved

ContextSwitchDeadlock was detected.

Posted on 2008-06-26
1
2,187 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Keep your audience engaged and get the most out of your next presentation with these quick Prezi tips.
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
Learn the basics of inputting and editing your text components in Prezi. We will cover how to set styles, position, and group your text components. In your Prezi editor, click anywhere on the canvas to add text: A flashing cursor informs you that yo…

726 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