C #: Simple Threading sample

Source: Internet
Author: User

1. Define thread classes and internal events

usingSystem;usingSystem.Collections.Generic;usingSystem.Text;usingSystem.Threading;usingSystem.Windows.Forms;namespacethreadsample{ Public Delegate voidThreadeventhandler (Objectsender, EventArgs e);  Public classMyThread {//thread execution Start call event         Public EventThreadeventhandler requestevent; //Thread execution End call event         Public EventThreadeventhandler completedevent; //whether to allow the execution of specific tasks in the thread         Public BOOLIsexecute =false; //Thread Name        Private stringThreadName ="Threads";//string. Empty;         Public stringThreadName {Get{returnThreadName;} }         Public voidStart () {Try            {                //invoke event before executionRequestevent ( This,NULL); if(isexecute) {//Perform TasksRandom seed =NewRandom (DateTime.Now.Millisecond); intSleeptime = seed. Next ( -, -);                Thread.Sleep (Sleeptime); } threadname+=Thread.CurrentThread.ManagedThreadId.ToString (); //invoke event after executionCompletedevent ( This,NULL); }            Catch(Exception ex) {//Logging error log trace files            }        }    }}
View Code

2. Thread is called externally and thread event content is added, and its monitor is implemented synchronously

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Threading;namespacethreadsample{ Public Partial classFrmapp:form { PublicFrmapp () {InitializeComponent (); }        Private voidBtnexit_click (Objectsender, EventArgs e) {Environment.exit (0); }        Private voidBtnrun_click (Objectsender, EventArgs e) {            Try            {                intThreadCount =Ten;  This. Tbmonitor.clear ();//displaying information for monitoring threadsmythread[] Threadarray =NewMythread[threadcount]; Thread TD=NULL;  for(inti =0; i < ThreadCount; i++) {Threadarray[i]=NewMyThread (); Threadarray[i]. Requestevent+=frmapp_requestevent; Threadarray[i]. Completedevent+=frmapp_completedevent; TD=NewThread (Threadarray[i].                    Start); Td.                Start (); }            }            Catch(Exception CE) {MessageBox.Show (CE).            ToString ()); }        }        //Log Thread Information        Private Delegate voidRecordseventhandler (Objectsender, EventArgs e); //display information on a per-thread-call method        Private voidFrmapp_completedevent (Objectsender, EventArgs e)//sender is too broad, can give exact name (MyThread)        {            if( This. tbmonitor.invokerequired) {                 This. Tbmonitor.invoke (NewRecordseventhandler (Frmapp_completedevent),New Object[] {sender, E}); }            Else            {                Try{Monitor.Enter ( This. Tbmonitor);//synchronization mechanism, specifying an object to get an exclusive lock//Specific Operation                     This. Tbmonitor.text + = (sender asMyThread). ThreadName +"--- ---"+ DateTime.Now.ToString ("YYYY-MM-DD HH:mm:ss.fffff") +Environment.NewLine; }                Catch(Exception ex) {MessageBox.Show (ex).                    ToString ()); //Logging error log trace files                }                finally{monitor.exit ( This. Tbmonitor);//synchronization mechanism, specifying object release exclusive lock                }            }        }        Private voidFrmapp_requestevent (Objectsender, EventArgs e) {            //whether to allow the execution of specific tasks in the thread(Sender asMyThread). Isexecute =true; }    }}
View Code

Note: The monitor implements whether the synchronized object must call the Invoke () method.

C #: Simple Threading sample

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.