multithreading - C# Threading issue & best practices -


this 1st time using threading in c# application. application checks bunch of web sites in list whether dead or alive.

here 1st attempt work multi-threading

    public void startthread(string url,int no)     {         thread newthread = new thread(() =>         {             begininvoke(new action(() => richtextbox1.text += "thread " + no + " running" + environment.newline));             bool b = ping(url);             if (b == true) { begininvoke(new action(() => richtextbox2.text += "okay" + environment.newline)); }             else             { return; }         });          newthread.start();     } 

i'm using above function create new threads , each thread created inside loop.

foreach (string site in website) { startthread(site,i); i++; // counter }

since i'm beginner have few questions.

  1. the code works fine i'm not sure if best solution
  2. sometimes threads run threads not return values method ping() checks host , returns true if online using webrequest. usual ?
  3. if ask user specify no of threads needs use , how can equally distribute work among threads ?
  4. is elegant way track status of thread, ( dead / alive ) ? use rocess.getcurrentprocess().threads.count;

1) solution ok. thread class has been partially superseded task class, if you're writing new code, can use that. there new in .net 4.5, called await .however, see 4).

2) ping method might crashing if website dead. can show code of method.

4)thread class nice because can check thread state, per requirements, using threadstate property - create list<thread> , put threads in it, , start them 1 one.

3)if want load number of threads input , distribute work evenly, put tasks in queue (you can use concurrentqueue has been suggested) , have threads load urls queue. sample code:

you initialize everything

void initialize(){ concurrentqueue<string> queue = new concurrentqueue<string>(); foreach(string url in websites) {     queue.enqueue(url); } //and threads list<thread> threads = new list<thread>(); (int = 0; < threadcountfromtheuser; i++) {     threads.add(new thread(work)); }}  //work method void work() {     while (!queue.isempty)     {         string url;         bool fetchedurl = queue.trydequeue(out url);         if (fetchedurl)             ping(url);     } } 

and run

foreach (thread t in threads) {     t.start(); } 

code not tested


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -