Use local variables wisely when calling anonymous functions asynchronously

Source: Internet
Author: User
Tags anonymous reflector thread

Problem: Bugs caused by using local variables outside of anonymous functions in multiple threads

Executing code

static void Main(string[] args)
{
    for (int i = 0; i < 10; i++)
    {
        Thread t = new Thread(delegate()
        {
            Thread.Sleep(new Random().Next(1, 10000));
            Console.Write(i + ", ");
        });
        t.Start();
    }
}

Will get output: 10, 10, 10, 10, 10, 10, 10, 10, 10, 10,

Rather than what we expect: 3, 5, 6, 1, 0, 7, 9, 8, 4, 2, such output. What is this for? (See the code for this bug in the actual project please refer to [1])

Analysis: Using reflector to view compiled code

The following is a code comparison before and after compilation. (Refer to [2] for specific methods of using reflector, here only show results)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.