multithreading - multiple threads calling wcf service -
below simple code start 5 threads, each 1 calls wcf service returns value sent in, problem :
public void clien_getdatacompleted(object sender, getdatacompletedeventargs e) { lock (sync) { count += e.result; } }
works ok , increments count, how capture when threads have completed, have simple example code on how call multiple wcf services use async methods.
public partial class threading : form { public int count; servicereference1.service1client clien = new servicereference1.service1client(); public threading() { initializecomponent(); } private void getdata() { clien.getdataasync(1); } public void displayresults() { messagebox.show(count.tostring()); } private object sync = new object(); public void clien_getdatacompleted(object sender, getdatacompletedeventargs e) { lock (sync) { count += e.result; } } public list<thread> runthreads(int count, threadstart start) { list<thread> list = new list<thread>(); (int = 0; <= count - 1; i++) { dynamic thread = new thread(start); thread.start(); list.add(thread); } return list; } private void button1_click_1(object sender, eventargs e) { clien.getdatacompleted += new eventhandler<getdatacompletedeventargs>(clien_getdatacompleted); threadstart wcfcall = new threadstart(getdata); ilist<thread> threads = runthreads(5, wcfcall); } }
many thanks
if using .net 4.0 can use task parallel library (tpl) , use tasks instead of threads. tasks has more flow control. can tasks like
// wait tasks finish. task.waitall(tasks);
here example on how use tasks , wait tasks finish. here
Comments
Post a Comment