21 Pages

Threads-CSharp

Course: CSE 681, Fall 2008
School: Syracuse
Rating:
 
 
 
 
 

Word Count: 766

Document Preview

Fawcett C#Threads Jim CSE681 Software Modeling & Analysis Fall 2002 ThreadClass Every Win32 thread is passed a function to run when created. terminates. When the thread returns from the function it In C#, Threads are managed by the System.Threading.Thread class. C# threads are passed a static or instance function of some C# class using a standard delegate of type ThreadStart....

Register Now

Unformatted Document Excerpt

Coursehero >> New York >> Syracuse >> CSE 681

Course Hero has millions of student submitted documents similar to the one
below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.

Course Hero has millions of student submitted documents similar to the one below including study guides, practice problems, reference materials, practice exams, textbook help and tutor support.
Fawcett C#Threads Jim CSE681 Software Modeling & Analysis Fall 2002 ThreadClass Every Win32 thread is passed a function to run when created. terminates. When the thread returns from the function it In C#, Threads are managed by the System.Threading.Thread class. C# threads are passed a static or instance function of some C# class using a standard delegate of type ThreadStart. StartingC#Threads Thread thread = new Thread(new ThreadStart(ThreadFunc)); thread.Start(); ThreadFunc can be: Static or instance member of the class instance that created the thread Static or instance member of some other class It must have the signature: void myThreadFunc(); You can supply parameters for thread operation as member data of the ThreadFuncs class. ExamplesofThreadStart ThreadFunc is a static member of TFClass: Thread thread = new ThreadStart(TFClass.ThreadFunc) ThreadFunc is a non-static member of TFClass: TFClass tfc; Thread thread = new ThreadStart(tfc.ThreadFunc); ThreadStates A thread that has been started, but not yet terminated can be in one of the following states: Running Waiting to run Suspended Blocked ThreadProperties IsBackground get, set Process does not end until all Foreground threads have ended. Background threads are terminated when application ends. Returns thread reference to calling thread Has thread started but not terminated? Highest, AboveNormal, Normal, BelowNormal, Lowest Unstarted, Running, Suspended, Stopped, WaitSleepJoin, .. CurrentThread get, static IsAlive get Priority get, set ThreadState get SharingResources A child thread often needs to communciate with its parent thread. It does this via some shared resource, like a queue. Parent Thread Sending Message to Child Child Thread Shared Queue Receiving Message from Parent Synchronization When two or more threads share a common resource access needs to be serialized - a process called synchronization. Consider the shared queue on the previous slide. Should the parent start to enqueue an element in an empty queue, but have its time-slice expire before finishing, the queues links are in an undefined state. Now, if the child thread wakes up, and attempts to dequeue an element the result is undefined. SynchronizationwithC#Lock // send messages to child thread string msg = ""; for(int i=0; i<50; ++i) { msg = "message #" + i.ToString(); Console.Write("\n Sending {0},",msg); // Enqueuing changes links so must lock lock(demo.threadQ) { demo.threadQ.Enqueue(msg); } // control writer speed - twice as fast as reader Thread.Sleep(50); } lock(demo.threadQ) { demo.threadQ.Enqueue("end"); } child.Join(); Console.Write( child "\n\n thread state = {0}\n\n",child.ThreadState.ToString() ); DemonstrationProgram QueuedMessages folder Illustrates communication between parent and child threads using a queue. Also illustrates use of C# lock operation. OtherLockingMechanisms The .Net Threading Library also provides: Monitor Locks an object, like C# lock, but provides more control. Provides atomic operations on 32 bit and 64 bit data types, e.g., ints, longs, pointers. Guards a region of code. Can synchronize across process boundaries. Allows fine-grained control of the sequencing of thread operations. Locks only when writing, allowing free reads. Interlocked Mutex AutoResetEvent and WaitOne ReaderWriterLock LockingCertainCollections ArrayList, Hashtable, Queue, Stack, and other collections provide Synchronized() function, supporting high performance locking. ArrayList unsync = new ArrayList(); ArrayList sync = ArrayList.Synchronized(unsynch); Your code needs no lock constructs with sync. MethodDecoration Methods can be decorated with a MethodImpl attribute, synchronizing access much like a Win32 critical section. [MethodImpl (MethodImplOptions.Synchronized)] string myMethod(string input) { } Note that this synchronizes a region of code, while lock and Monitor synchronize objects. WinFormsandWorkerThreads A UI thread is a thread that creates a window. A worker thread is a thread spawned by a UI thread to do work in the background while the UI thread services UI messages. functions directly. It accesses them through Forms Invoke, BeginInvoke, and EndInvoke functions, passing a delegate as an argument. A worker thread must never access UI BeginInvokeExample for (i = 1; i <= 25; i++) { s = "Step number " + i.ToString() + " executed"; Thread.Sleep(400); // Make asynchronous call to main form. // // // // MainForm.AddString function runs in main thread because we activated the delegate through form's BeginInvoke function. To make synchronous call use Invoke. Delegate arguments passed as an array of objects m_form.BeginInvoke(m_form.m_DelegateAddString, new Object[] {s}); // check if thread is cancelled if ( m_EventStop.WaitOne(0, true) ) { // clean-up operations may be placed here // ... // inform main thread that this thread stopped m_EventStopped.Set(); return; } } DemonstrationPrograms ProcessDemo Illustrates creating a child process Worker Thread folder Simple Demonstration of UI and Worker thread communication using Form.Invoke() FormInvokeDemo folder A more interesting demonstration of the above. QueuedMessages Illustrates communication between threads using queues and the C# lock operation. EndofPresentation
Find millions of documents on Course Hero - Study Guides, Lecture Notes, Reference Materials, Practice Exams and more. Course Hero has millions of course specific materials providing students with the best way to expand their education.

Below is a small sample set of documents:

Syracuse - CSE - 686
Advanced CMark Sapossnek#CS 594 Computer Science Department Metropolitan College Boston UniversityPrerequisites This module assumes that you understand the fundamentals ofProgrammingVariables, statements, functions, loops, etc.Objec
Syracuse - CSE - 686
The Common Language Runtime (CLR)Mark Sapossnek CS 594 Computer Science Department Metropolitan College Boston UniversityPrerequisites Overview of .NETLearning Objectives Understand the breadth of services that the Common Language Runtime prov
Syracuse - CSE - 686
.NET Application Design ConsiderationsMark Sapossnek CS 594 Computer Science Department Metropolitan College Boston UniversityPrerequisites This module assumes that you understand the fundamentals of: Object-oriented programming C# ADO.NET
Syracuse - CSE - 686
Introduction to CMark Sapossnek CS 594 Computer Science Department Metropolitan College Boston University#Prerequisites This module assumes that you understand the fundamentals ofProgrammingVariables, statements, functions, loops, etc.
Syracuse - CSE - 686
.NET Framework Advanced TopicsName Title Department CompanyPrerequisites This module assumes that you understand the fundamentals of:ProgrammingVariables, statements, functions, loops, etc. Classes, inheritance, polymorphism, members, etc.
Syracuse - CSE - 686
XMLMark Sapossnek CS 594 Computer Science Department Metropolitan College Boston UniversityLearning Objectives Learn what XML is Learn the various ways in which XML is used Learn the key companion technologies Learn how to use the .NET framewo
Syracuse - CSE - 778
CSE791AdvancedWindowsProgrammingSummer2003ComparisonofdifficultyforAdvancedWindowsProjectsProject 1.SlideViewer 2.CodeFormatter 3.ModuleBuilderAddIn 4.PictureGallery 5.SourceCodePrinting 6.DirectoryManager 7.HTMLEditor 8.StickFigureAnimation 9.N
Syracuse - CSE - 778
CSE 791 Advanced Windows ProgrammingSummer 1999Final Projects Grade SheetName: Project # Meets Requirements Ease of Use Presentation of Design Project # Meets Requirements Ease of Use Presentation of Design Project # Meets Requirements Ease of
Syracuse - CSE - 681
CSE681 Software Modeling and AnalysisFall 2002Architectural Report Brief AnalysisProject # Name:1. Effective use of diagrams, effective discussion: 1-5 points each a. Context, DFDs, Module diagram b. Operation, Structure Charts, Views c. Act
Syracuse - CSE - 681
C#ProgrammingLanguage OverviewJimFawcett CSE681SWModeling&amp; Analysis Fall2002C#LanguageLooksalotlikeJava.Astronganalogybetween: JavaVirtualMachine&amp;.NetCLR Javabytecodes&amp;.NetIntermediateLanguage Javapackages&amp;CRLcomponentsandassemblies
Syracuse - CSE - 681
Dependency Analysis Use CasesJim Fawcett CSE681 SW Modeling &amp; Analysis Fall 2002 BackgroundThis presentation is concerned with dependencies between a program's modules.A typical module should consist of about 400 source lines of code.
Syracuse - CSE - 686
Handouts/CSE686/lecture2/Client and Server ScriptPurpose:Illustrate how to use JavaScript on both browser client and web server. Jim Fawcett CSE686 Internet Programming Summer 2007
Syracuse - CSE - 686
Syracuse - CSE - 686
Handouts/CSE686/lecture2Active Server Pages: Serverside ScriptingASP = HTML with some JavaScript or VBScriptPurpose:Illustrate use of serverside scripting to make web pages dynamic.Jim Fawcett CSE686 Internet Programming Summer 2007
Syracuse - CSE - 686
Handouts/CSE686/lecture2Dynamic HTMLPurpose:Illustrate use of serverside scripting to make web pages dynamic. Almost all of the scripting presented in these examples runs on the browser client.Jim Fawcett CSE686 Internet Programming Summer
Syracuse - CSE - 686
Handouts/CSE686/Lecture2/Aspex1,3,4,5.asp,test.aspFirstASPApplicationsPurpose:IllustratecreationofHTML,usingservercontext,withASPscripts, toprovidedynamicresponsestoclientinputs.JimFawcett CSE686InternetProgramming Summer2006
Syracuse - CSE - 686
Handouts/CSE686/lecture2MoreDynamicHTMLPurpose:Illustrateuseofserversidescriptingtomakewebpagesdynamic. Almostallofthescriptingpresentedintheseexamplesrunsonthe browserclient.JimFawcett CSE686InternetProgramming Summer2007
Syracuse - CSE - 686
Browser and Server ModelsJim FawcettCSE686 Internet Programming Summer 2005 Topics Web Programming Model Browser Model Server Model Client/Server - Current Web Model Client ComputerInternet Information ServerWindows 2000 Serv
Syracuse - CSE - 686
DHTMLex1 and ASPex2
Syracuse - CSE - 686
DHTMLex2
Syracuse - CSE - 686
DHTMLex3
Syracuse - CSE - 686
Syracuse - CSE - 686
HTMLPage0.7.htmHTMLPage0.7.htmHTMLPage0.7.htmHTMLPage0.7.htmHTMLPage0.7.htmHTMLPage0.7.htmHTMLPage0.7.htmHTMLPage0.7.htmHTMLPage0.7.htm
Syracuse - CSE - 686
Syracuse - CSE - 687
CSE687ObjectOrientedDesignSpring2003CommonProjectErrorsName: Missing,inaccurate,orincomplete buildprocess Requiredfilesstatementon maintenancepagedoesnotinclude thisfileorsomeofitsincludedlocal files. Failstocompile Fails to run successfully No
Syracuse - CSE - 382
CSE382 Algorithms and D ata Structures RemediationCST 3-216 Thursday, May 15CSE382 Spring 2008 grades have been posted. You are here because you failed that course. We are here to discuss one option for you to recover. You can satisfy your requir
Syracuse - CSE - 382
New Laboratory 2 TreesWikipedia 1 defines a tree as: In graph theory, a tree is a graph in which any two vertices are connected by exactly one path . Alternatively, any connected graph with no cycles is a tree. A forest is a disjoint union of trees
Syracuse - CSE - 382
NewLaboratory3RedBlackBinarySearchTreesWikipedia1definesaredblacktree2as: Aredblacktreeisatypeofselfbalancingbinarysearchtree,adatastructureusedin computerscience,typicallyusedtoimplementassociativearrays.Theoriginalstructurewas inventedin1972byRudo
Syracuse - CSE - 681
.NetRemotingJim Fawcett CSE681 Software Modeling &amp; Analysis Fall 2002ReferencesProgramming Microsoft .Net, Jeff Prosise, Microsoft Press, 2002, Chap 15.http:/samples.gotdotnet.com/quickstart/howto/.NetRemotingRemoting supports
Syracuse - CSE - 681
Notice!I will not hold a Help session this week.The TA office hours and help sessions will go on as scheduledMy normal help sessions from 9:00 12:00 Noonon Thursdays will resume rd October 3
Syracuse - CSE - 681
CSE681 Software Modeling and Analysis Project #4 Component ServerFall 2002 due 6 November 2002Purpose: This project requires you to develop a component server program. A component server is a machine running a program t