Operating system threads vs. Process operations (C #)

Source: Internet
Author: User

September 08 Admission, July 12 graduation, ended my happy and rich university life in the Software Institute. This series is a review of the four-year professional curriculum study, indexed in: http://blog.csdn.net/xiaowei_cqu/article/details/7747205


Threads and Processes

A procedure to design the following requirements for the contents of the Process class and thread classes in MSDN in C #:

Open two background threads (BACKGROUND=FALSE) in the program, control two process classes, and use these two classes to cycle and close the processes separately, and record the corresponding information in the foreground panel

For example: Open two background threads A and B, instantiate a process class PA in a thread, instantiate a process class PB in B thread. Then two threads enter the loop at the same time, respectively, to do the following:

Open the Notepad program with PA and record all the available information for the Notepad process, then close and record the information, open the Notepad program, and record all the available information for the Notepad process, and then close and record the information ... (Make a dead loop) record the process that you control to create, run, end time and PCB information

Use PB to open the Calculator program, and record all the display information of the Notepad process, then close and record the information, then open the Notepad program, and record all the information that can be displayed in the Notepad process, then close and record the information ... (Make a dead loop) record the process that you control to create, run, end time and PCB information

Attached: The foreground form name is your name and the school number, the control program is not limited to Notepad and calculator, in the completion of the basic content of the program on the basis of functional modification can be added "Experimental steps"

1. Check out C # in MSDN about process classes and thread classes

MSDN has a detailed explanation of process classes and a description of attributes, and there are examples (thread is relatively simple), no longer repeat here.

The process component provides access to processes running on the computer.

A process is a running application, or a container, that, after the application is run, is the equivalent of loading the application into a container (you can also load variable data, referenced DLL files, and so on). A thread is the basic unit in which the operating system allocates processor time to a process. Any code that the thread can execute the process, including the part currently executed by the other. such as starting, stopping, monitoring applications, and so on.

2. Create background thread A, instantiate a process class PA, loop open close Notepad, and record information

Thread A;
            A = new Thread (new ThreadStart (Exenotepad)); 
            A.isbackground = true;

A.start ();
Declares a delegate to resolve the InvalidOperationException exception delegate void Setrtbhandler (string s) that the control binds to a specific thread; private void Setrtb (string s) {Tabpage2.controls[0].
Text + S;
  ///<summary>///Loops Open and close the Notepad process ¬///</summary> private void Exenotepad () {process Pa;
    try {int i = 1;
        while (true) {/open and close Notepad program Pa = Process.Start ("notepad");
       Sa= "" "+ i +" Secondary Open Notepad program "+" \ n ";
         Sa= Printprocessinfo (Pa) + "\ n" + "\ n"; This attempts to directly display on the RichTextBox, but always throws the exception//cross-thread operation not Valid:control ' richTextBox1 ' accessed ' a thread//other t  Han the thread it was//solution is to use the delegate if (this.richTextBox1.InvokeRequired) {Setrtbhandler cal = Delegate (string s) {Tabpage2.controls[0]. Text + SA;
           }; This.
           Invoke (Cal, new object[] {SA}); This. Invoke (New Settexthandler (settext), NEW object[] {C.S}); } else {This.tabpage2.controls[0].
        Text + SA;
                    
        } pa.kill ();
         Pause for half a second System.Threading.Thread.Sleep (1000);
       i++; } catch (Exception ex) {MessageBox.Show (ex).
    message);
 }

}

3. function to get the corresponding information of the process

<summary>///functions that display process-related information the display of each piece of information in the///function is placed in a try Catch statement///Although it is redundant, it enhances interactivity and displays the normative///</summary>// /<param name= "process" ></param>///<returns></returns> private String Printprocessinfo (
  Process process) {string str= "";
  STR + + "process number:"; TRY{STR + + process.
  Id.tostring () + "\ n";} catch (Exception ex) {str = str + ex. Message + "\ n";
  str + = "process name:"; TRY{STR + + process.
  Processname.tostring () + "\ n";} catch (Exception ex) {str = str + ex.

  Message + "\ n";}
  STR + + "Start time:"; TRY{STR + + process.
  Starttime.tostring () + "\ n";} catch (Exception ex) {str = str + ex. Message + "\ n";
  str + = "Exit Time:"; TRY{STR + + process.
     Exittime.tostring () + "\ n"; STR + + "Run Time:" + (Process). Exittime-process. StartTime).
   ToString () + "\ n";} catch (Exception ex) {str = str + ex.
         Message + "\ n"; STR + + "Run Time:" + (datetime.now-process. StartTime).

   ToString () + "\ n";}
   str = "Main module of process:"; TRY{STR + + process. Mainmodule.tostRing () + "\ n";} catch (Exception ex) {str = str + ex. Message + "\ n";
   The main window title of STR + + process: "; TRY{STR + + process.
   Mainwindowtitle.tostring () + "\ n";} catch (Exception ex) {str = str + ex.

   Message + "\ n";}
   STR + + "process loading module:"; TRY{STR + + process.
   Modules.tostring () + "\ n";} catch (Exception ex) {str = str + ex.

   Message + "\ n";}
   STR + + dedicated memory size for process: "; Try{str + = convert.tostring (process.
   privatememorysize/1024) + "K" + "\ n";} catch (Exception ex) {str = str + ex.

   Message+ "\ n";}
   str = = "Virtual memory size of process:"; Try{str + = convert.tostring (process.
   peakvirtualmemorysize64/1024) + "K" + "\ n";} catch (Exception ex) {str = str + ex.

   Message + "\ n";} 
   STR + + "amount of paged memory allocated for the process:"; Try{str + = convert.tostring (process.
   pagedmemorysize64/1024) + "K" + "\ n";} catch (Exception ex) {str = str + ex.

   Message + "\ n";} 
   str + = "Paging system memory Size:"; Try{str + = convert.tostring (process.
   pagedsystemmemorysize64/1024) + "K" + "\ n";} catch (Exception ex) {str = str + ex. Message +"\ n";}
   Maximum amount of memory paging file for STR + + process: "; Try{str + = convert.tostring (process. peakpagedmemorysize64/1024) + "K" + "\ n"; catch (Exception ex) {str = str + ex.

    Message + "\ n";} 
    Maximum allowable working set size for str = + process:; TRY{STR + + process.
    Maxworkingset.tostring () + "\ n";} catch (Exception ex) {str = str + ex.

    Message + "\ n";} 
    The minimum allowable working set size for str = = "process:"; TRY{STR + + process.
    Minworkingset.tostring () + "\ n";} catch (Exception ex) {str = str + ex.

    Message + "\ n";} 
    STR + + "Process physical memory usage:"; Try{str + = convert.tostring (process.
    workingset/1024) + "K" + "\ n";} catch (Exception ex) {str = str + ex.

     Message + "\ n";}
     STR + + "The basic priority of the process:"; TRY{STR + + process.
     Basepriority.tostring () + "\ n";} catch (Exception ex) {str = str + ex.

     Message + "\ n";}
     STR + + "The overall priority category for the process:"; TRY{STR + + process.
     Priorityclass.tostring () + "\ n";} catch (Exception ex) {str = str + ex.

     Message + "\ n";}
     STR + + "process Privileged processor Time:"; TRY{STR + + process. Privilegedprocessortime.tosTring () + "\ n";} catch (Exception ex) {str = str + ex.
            
Message + "\ n";}
return str;
 }

4. Same way create thread B and instantiate the process class PB

5. Additional function: Task Manager Simulation

private void Getprocessinfo () {listview1.view = View.Details;
            LISTVIEW1.COLUMNS.ADD ("image name"); Listview1.columns[0].
            Width = 150;
            LISTVIEW1.COLUMNS.ADD ("Process id");
            LISTVIEW1.COLUMNS.ADD ("Number of threads");
            LISTVIEW1.COLUMNS.ADD ("priority");
            LISTVIEW1.COLUMNS.ADD ("Physical Memory");
            LISTVIEW1.COLUMNS.ADD ("virtual memory");
                try {listView1.Items.Clear ();
                process[] allprocess = process.getprocesses ();
                string[] Proinfo = new String[6];
                    foreach (Process p in allprocess) {proinfo[0] = P.processname;
                    PROINFO[1] = p.id.tostring ();
                    PROINFO[2] = p.threads.count.tostring ();
                    PROINFO[3] = p.basepriority.tostring ();
                    PROINFO[4] = convert.tostring (p.workingset/1024) + "K"; PROINFO[5] = convert.tostring (p.virtualmemorysize/1024) + "K";

                    ListViewItem LVI = new ListViewItem (proinfo, "process");
                LISTVIEW1.ITEMS.ADD (LVI); } catch (Exception ex) {MessageBox.Show (ex).
            message);	
 }
        }

Additional features: Saving record information

private void Save Toolstripmenuitem_click (object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog Savedlg = New SaveFileDialog ();
                Savedlg.title = "Save As:";
                Savedlg.overwriteprompt = true;
                Savedlg.filter = "text file (*.txt) |*.txt";
                Savedlg.showhelp = true;
                if (savedlg.showdialog () = = DialogResult.OK)
                {
                     string filename=savedlg.filename;
                     using (StreamWriter sw = new StreamWriter (filename))
                     {
                         sw. Write (this.tabpage2.controls[0). Text);
            }} catch (Exception ex)
            {
                MessageBox.Show (ex. message);
            }
            
        

"Experimental screenshot"

Overall screenshot


Task Manager screenshot


"Result Analysis"

The experiment experimented with the basic operations of some process threads by using the processes and thread classes in C #. Have a more specific understanding of the threads and process concepts

2. At the same time feel C # will process and thread classes are encapsulated more comprehensive, it is convenient to do a lot of useful processing. For example, the original thought would be "very low-level" task Manager "cottage version" effect, with a process.getprocesses () also came out. In addition, simply try to use WMI technology for system management and optimization of programming, found also very simple. (Not much in the report, given that it's irrelevant)

3. The experience of multithreaded programming is not much, and the use of delegates in experiments is the first attempt. Also deeply aware of the importance of exception handling, the operation of the occasional throw out the unusual, it is really annoying things.

4. Feel that there are many operations not carefully tried, such as interrupt thread interrupt () block join (), now have a general understanding of the basic operations, and so on when needed to study it carefully. Reprint Please indicate the source: http://blog.csdn.net/xiaowei_cqu/article/details/7041212 Program source and experiment report download: http://download.csdn.net/detail/xiaowei_cqu/3880877

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.