1

I try to use tasks with code:

public partial class Form1 : Form
{
    public ConcurrentStack<long> journal = new ConcurrentStack<long>();
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Task[] tasks = new Task[10];
        for (long i = 0; i < 10; i++)
        {
            tasks[i] = Task.Factory.StartNew(() => getJournal(i));
        }
        Task.WaitAll(tasks, 60000);
        List<long> list = journal.ToList();
        textBox1.SuspendLayout();
        foreach (long l in list)
        {
            textBox1.AppendText(l.ToString("### ### ### ### ") + Environment.NewLine);
        }
        textBox1.ResumeLayout();

    }
    public void getJournal(long val)
    {            
        journal.Push(val);
    }
}

But in textBox I get something like: 10 10 10 10 10 10 10 3 3 2

sometimes only 10's or something else

I don't understand why ... (in my opinion it should be 1 2 3 4 5 6 7 8 9 - not in order ofc...)

Nash Carp
  • 169
  • 12
barpas
  • 75
  • 1
  • 9
  • The `for`-loop just proceeds faster than the newly started `task`, thats why `i` gets incremented and every task prints out 10. You can test this out by simply putting a Thread.Sleep(10) after the `.StartNew()` line. – oRole Nov 06 '17 at 09:59

0 Answers0