J
J
jackroll2015-06-23 19:36:06
C++ / C#
jackroll, 2015-06-23 19:36:06

Parallel.ForEach not running on new thread?

public MainForm()
{
    InitializeComponent();
    this.Text = string.Format("current thread #{0}",
                Thread.CurrentThread.ManagedThreadId);
}

private void button1_Click(object sender, EventArgs e)
{
    ProcessFiles();
}

private void ProcessFiles()
{
    string[] files = Directory.GetFiles(@"F:\Troelsen\asd", "*.jpg", SearchOption.AllDirectories);
    string newDir = @"F:\Troelsen\asd\Modified";
    Directory.CreateDirectory(newDir);
    
    Parallel.ForEach(files, currentFile =>
    {
        //Thread.CurrentThread.Name = "Parallel.ForEach";
        string filename = Path.GetFileName(currentFile);
        using (Bitmap bitmap = new Bitmap(currentFile))
        {
            bitmap.RotateFlip(RotateFlipType.Rotate180FlipNone);
            if (filename != null) bitmap.Save(Path.Combine(newDir, filename));
        }
        this.Invoke((Action) delegate
        {
            this.Text = string.Format("current thread #{0}",
                Thread.CurrentThread.ManagedThreadId);
        });
    });
}

I click on button1 and the application freezes, even after processing all .jpg files.
Code taken from Andrew Troelsen's book "Pro C# 5.0 and the .NET 4.5 Framework"

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Lastochkin, 2015-06-23
@jackroll

The code

this.Text = string.Format("current thread #{0}",
                Thread.CurrentThread.ManagedThreadId);

will always be executed on the UI thread (via Invoke() though!)
Correct:
var text =  string.Format("current thread #{0}", Thread.CurrentThread.ManagedThreadId);
this.Invoke(()=> Text = text);

BTW, Parallel.ForEach() etc. operations in separate streams are not guaranteed at all - read Richter.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question