0

I have a problem with multi-thread Below is my c# code:

    private static readonly object ThreadKey = new object();

    private void PlayVideo()
    {
        int count = 0;

        for (int y = 1; y < 1000; y++)
        {
            lock(ThreadKey)
            {
                count++;
                if ((count % 100) == 0)
                {
                    Task.Run(() => TestTh(count));
                }
            }
         
        }
    }
    private void TestTh(int count)
    {
        //i find count is not a multiple of 100
        System.IO.File.WriteAllText(@"D:\USER\Desktop\Myfolder\" + count.ToString()+".txt", count.ToString());
    }

i find the variable 'count' in TestTh() function is not a multiple of 100 Can anyone explain this phenomenon?

please help me,thanks

I have locked count ,but it is not work

jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
  • 1
    The LINQ `() => TestTh(count)` captures the variable `count` and will use the value it has when it comes to execute it. See https://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ for details. You may assign `count` to a valiable with scope within the `for` and then use this variable to fix it. – Klaus Gütter Apr 17 '23 at 04:29
  • Does this answer your question? [Captured variable in a loop in C#](https://stackoverflow.com/questions/271440/captured-variable-in-a-loop-in-c-sharp) – Charlieface Apr 17 '23 at 12:06

0 Answers0