c# - create new Thread, passing two parameters -
i'm trying create new thread passing 2 parameters, have searched many times still no result. here method:
public void add(int smallest, int biggest) { (int = smallest; < biggest+1; i++) { thread.sleep(500); result = result + i; } } and want below:
static void main() { int x=10; int y=100; // in line appear error thread t=new thread(add); t.start(x,y); }
you can't way. thread.start() method doesn't include overloads supporting more 1 parameter.
however, general goal solved using anonymous method thread body:
static void main() { int x=10; int y=100; // in line appear error thread t=new thread(() => add(x, y)); t.start(); } i.e. instead of add() method being thread entry point, wrap in anonymous method (declared here via lambda expression syntax). arguments x , y "captured" anonymous method, passed add() method when thread starts.
one important caution: values variables retrieved when add() method called. when thread starts. if modify values before happens, new values used.
this idiom usable in context want pass strongly-typed and/or multiple arguments method api allow none or fixed number (like one). event handlers, task entry points, i/o callbacks, etc. can benefit approach.
Comments
Post a Comment