multithreading - multiple threads calling same method in c# -


i have following c# code snippet in have simulated problem.in program have service function call readrooms method. calling service method on different threads.i expecting both servicecall , readrooms method fired equally getting below result not correct.

enter image description here

using system; using system.collections.generic; using system.linq; using system.text; using system.threading; using system.threading.tasks;  namespace consoleapplication1 {     class program     {         public static void readrooms(int i)         {             console.writeline("reading room::" + i);             thread.sleep(2000);         }         public static void callservice(int i)         {             console.writeline("servicecall::" + i);             readrooms(i);          }         static void main(string[] args)         {             thread[] ts = new thread[4];             (int = 0; < 4; i++)             {                 ts[i] = new thread(() =>                     {                         int temp = i;                         callservice(temp);                       });                 ts[i].start();             }             (int = 0; < 4; i++)             {                 ts[i].join();             }             console.writeline("done");             console.read();          }     } } 

you still 'capturing loop variable'. creating temp late, when i captured.

try this:

for (int = 0; < 4; i++) {    int temp = i;              // outside lambda    ts[i] = new thread(() =>    {         //int temp = i;       // not here         callservice(temp);    });    ts[i].start(); } 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -