Problem with Invoke to parallelize foreach

I have a problem using System.Threading.Tasks.Parallel.ForEach. The foreach progressBar body wants to update. But the Invoke method sometimes freezes.

I am attaching the code to a form that is prograssbar and Buton.

private void button1_Click(object sender, EventArgs e)
{
    DateTime start = DateTime.Now;
    pforeach();
    Text = (DateTime.Now - start).ToString();
}


private void pforeach()
{
    int[] intArray = new int[60];
    int totalcount = intArray.Length;
    object lck = new object();
    System.Threading.Tasks.Parallel.ForEach<int, int>(intArray,
    () => 0,
    (x, loop, count) =>
    {
        int value = 0;
        System.Threading.Thread.Sleep(100);
        count++;
        value = (int)(100f / (float)totalcount * (float)count);

        Set(value);
        return count;
    },
    (x) =>
    {

    });
}

private void Set(int i)
{
    if (this.InvokeRequired)
    {
        var result = Invoke(new Action<int>(Set), i);
    }
    else
        progressBar1.Value = i;
}

Sometimes it passes without problems, but usually it freezes var result = Invoke (new Action <int> (Set), i). Try kicking me in trouble.

Thank.

+3
source share
2 answers

, Invoke ( Task TaskScheduler) , . . Parallel.ForEach. .

, Parallel.ForEach , Task :

private TaskScheduler ui;
private void button1_Click(object sender, EventArgs e) 
{
    ui = TaskScheduler.FromCurrentSynchronizationContext();
    DateTime start = DateTime.Now;
    Task.Factory.StartNew(pforeach)
        .ContinueWith(task =>
        {
            task.Wait(); // Ensure errors are propogated to the UI thread.
            Text = (DateTime.Now - start).ToString(); 
        }, ui);
} 

private void pforeach() 
{ 
    int[] intArray = new int[60]; 
    int totalcount = intArray.Length; 
    object lck = new object(); 
    System.Threading.Tasks.Parallel.ForEach<int, int>(intArray, 
    () => 0, 
    (x, loop, count) => 
    { 
        int value = 0; 
        System.Threading.Thread.Sleep(100); 
        count++; 
        value = (int)(100f / (float)totalcount * (float)count); 

        Task.Factory.StartNew(
            () => Set(value),
            CancellationToken.None,
            TaskCreationOptions.None,
            ui).Wait();
        return count; 
    }, 
    (x) => 
    { 

    }); 
} 

private void Set(int i) 
{ 
    progressBar1.Value = i; 
} 
+4

, , :

:

TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();

:

    private void changeProgressBar()
    {
        (new Task(() =>
        {
            mainProgressBar.Value++;
            mainProgressTextField.Text = mainProgressBar.Value + " of " + mainProgressBar.Maximum;
        })).Start(uiScheduler);
    }

Invoke, Task, .

, System.Threading.Tasks;

+1

Source: https://habr.com/ru/post/1759319/


All Articles