Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

ContextSwitchDeadlock was detected.

Posted on 2008-06-26
1
Medium Priority
?
2,412 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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Learn how to set up basic frames and paths in Prezi and understand the open space that Prezi allows you to create presentations in.
Learn how to download your full Prezi presentation for offline presenting. Prezi doesn’t have to be viewed and shared in a web browser, even with a free account you can download your full presentation to share with others. Be sure to download any vi…
Suggested Courses
Course of the Month20 days, 19 hours left to enroll

810 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