Solved

ContextSwitchDeadlock was detected.

Posted on 2008-06-26
1
2,119 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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
HTTPS jquery doesn't work 9 61
Call Controller Action Method from ASPX 2 14
Release Dynamically Allocated Memory in C# 3 25
JSON  parse help 7 25
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
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 how to set up basic frames and paths in Prezi and understand the open space that Prezi allows you to create presentations in.

770 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