University of Wisconsin–Parkside: Computer Science



.NET C# Threads

Introduction

This document has the following sections to help students in completing homework assignments:

• C# Lab 1: Creating a Web Browser: Creating your first C# program using a form. This is at the END of the file.

• Create Threads in C#: Introduction to threads in C#

• Synchronizing Threads: Mutexes, Semaphores, Locked critical sections…

• Modifying an Existing Program: Copying a program for modification

• File Manipulation: Reading and writing files (containing strings)

Creating Threads in C#

To work with threads, it is important to include at the top of the file:

using System.Threading;

To create a thread in C#, it is necessary to pass an object.function() (or a pointer to a function, called a ‘delegate’) to the constructor. Below, the object.function() is this.laugh(), which takes 0 parameters. It is possible to instead create a new object, initialize the object to describe what the thread shall do, and then start the thread. The thread is started with the threadObject.Start() function.

Thread t = new Thread(this.laugh);

t.Start();

t.Join( ); // Join both threads with no timeout

The function to be invoked must be defined as a void function(), for example:

public void laugh() { …}

Often a programmer wants to print the ID of the thread during debugging. This can be done using the GetHashCode() function. Alternatively, a Name can be defined using the Name property (or attribute). Then the name can be printed, when desired:

Thread.CurrentThread.GetHashCode();

Thread.CurrentThread.Name = “1”;

Other properties include: Priority, ThreadState, IsAlive, IsBackground.

Threads can put themselves to sleep. Below, the thread will sleep for 5 seconds.

Thread.Sleep(5000); // or …

System.Threading.Thread.Sleep(5000);

Synchronizing Threads

Here are three ways to implement Mutual Exclusion. One way is to use the lock(this) {} block. In this case, only one thread can be active in the ‘locked’ code.

Function()

{

lock (this) {



}

}

Another way of ensuring mutual exclusion is to use a Monitor construct. The Monitor.Enter and Monitor.Exit is equivalent to a lock (this) { }. The mutually exclusive code is put in the try {} block.

Function()

{

Monitor.Enter(this);

try { … }

finally { Monitor.Exit(this); }

}

A third method is to define the whole class as synchronized. Then only one function at a time can enter ANY of the functions.

using System.Runtime.Remoting.Contexts;



[Synchronization]

public class Laugh : ContextBoundObject

{

Public void Laughing() {}

}

Semaphores and Mutexes exist too. The syntax for a Semaphore is:

// Class attribute sem…

Semaphore sem = new Semaphore(initialValue, maxCount);

sem.WaitOne();

critical section…

sem.Release();

Syntax for a Mutex (which is automatically initialized to 1) is:

// Class attribute mutex…

private Mutex mutex = new Mutex();

mutex.WaitOne();

critical section…

mutex.ReleaseMutex();

Rules for working with threads:

• Only the main thread can access the user interface (forms, etc). This prevents many race conditions.

• Exceptions must be caught and handled, or the application will be terminated.

• Thread pools enable threads to be recycled, instead of creating/destroying them. This is faster. Use BeginInvoke() and EndInvoke() calls. These calls also enable parameters to be passed to the delegate function.

Modifying an Existing Program

Double click the .sln (or Solution) file to start the program, assuming Microsoft Visual Studio is available.

Any C# code uses the extension .cs. For example, form1.cs has the C# code for behind the form, including any functions that are to be called as buttons are pressed or text is entered on the forms. Within form1.cs, there is one function automatically created by .NET for each button to be pressed or box to have text entered.

The executable is within the bin directory. It will only run if the proper versions of .NET libraries are available. If you port an executable to your home laptop where you don’t have these libraries available, the .NET code will not execute. However, the .NET libraries can be downloaded from a Microsoft web page for free.

Since the syntax for C# is similar but not the same as Java, it is often best to use the Intellisense feature. As you type, alternative choices (e.g., functions, attributed) are made available to you, as long as the objects you are using are already defined.

Creating a Web Form

How to create the web form application.

Open Microsoft Visual Studio 2010-> Microsoft Visual Studio 2010

Select: New Website

Select: Empty Web Site

Select the proper options: C#, and the file location to retain files

You will see the Solution Explorer on the top right side,

The Properties on the bottom right side

The Toolbox on the far left side.

Create a form by right-clicking on the Solution Explorer.

Add New Item -> Web Form

The web page appears as an HTML form. Select the Design option below the web page.

In Design:

Enter “Welcome to the Calendar Program” at the form’s prompt.

Enter a few carriage returns, and then: “Enter schedule about this date”

Select Toolbox -> TextBox, and drag and drop the TextBox below the question.

Select Toolbox -> Button and drag and drop the Button next to the TextBox.

In the Properties area, set the Button’s “Text” (name) to “Go”.

Add more carriage returns to create more space.

Select Toolbox -> Label and drag and drop the Label below the Button.

Resize the Label to a Height of 100 and Width of 600 Pixels.

Rename the Label’s Text to “Schedule”.

Select Toolbox -> Calendar and drag and drop a Calendar below the Label area.

You may change colors on each item in the Properties area, if you like.

Using the Format Drop Down Menu, you may change the form’s Background Color

Programming the Code-Behind:

Double click the Go Button. A function will be created.

Add the following code, where the inserts an HTML break-line:

Label1.Text += "" + TextBox1.Text;

Return to Design. Double click the Calendar Button.

Add the following code:

Label1.Text = Calendar1.SelectedDate.ToLongDateString();

To execute the form, select:

Build->Build Solution

Debug->Start without Debugging (or Start with Debugging)

Enhance as follows:

When the Go Button is pressed, the TextBox should clear.

When the form is entered, read a file into Label1.

File Manipulation

The file manipulation described in this section is to read and write strings. To learn about other file manipulation classes, please refer to a text.

First, all file manipulation is in the System.IO library. You may specify this library at the top of your code or you may specify the full library every time you want to use an item within it:

using System.IO;



StringWriter fout = new StringWriter(“filename.txt”);

Or:

System.IO.StringWriter fout = new System.IO.StringWriter(“filename.txt”);

StringWriter functions include: Close(), Flush(), Write(), WriteLine().

A string reader class exists also:

string directory = "C:/Users/…/Easy.txt";

StreamReader fin = new StreamReader(directory);

string input = null;

while ((input = fin.ReadLine()) != null)



Other functions include Peek(), Read(), ReadBlock(), ReadToEnd().

The BinaryWriter and BinaryReader allow reading and writing to a binary file.

Sample Code:

public static string GetText(string filename)

{

string directory = "C:/Documents and Settings/My Documents/…

/App_Data/" + filename;

StreamReader fin = new StreamReader(directory);

buffer = fin.ReadLine();

return buffer;

}

Random Number Generation

The following sample code creates and obtains a random integer.

Random r = new Random();

int count = r.Next();

To print count, use count.ToString();

C# Lab 1: Creating a Web Browser

To open MS Visual Studio:

Start->All Programs->Microsoft Visual Studio 2010->MS Visual Studio 2010

To start a new project open:

New Project

In the next screen you will specify to use C# for a Windows Application, and name the program:

Select: Visual C#, Windows Form Application

Name=WebBrowser

Press OK

In the next screen a form (“Form1”) will appear. You can make your screen somewhat bigger by dragging its edge.

Look for the ‘Toolbox’ on the far left side of the screen. It contains ‘Button’, ‘Checkbox’, …

Drag and drop a ‘Button’ onto the form. Look for the ‘Properties’ window on the bottom right side of your screen. Within Properties, set the following values:

Text=Go

(Name)=GoButton

Be sure to do an Enter after entering the values so that the value sticks.

You have just given a ‘Text’ label to the button and a name you will use in your program: GoButton. You may also change the color of the button if you like, by finding and changing the appropriate property.

Drag and drop a ‘Label’ onto the form. Move the label to the top of the form. Within the Properties window, set the following values:

Text=Enter URL and Press Go

(Name)=Directions

Drag and drop a ‘TextBox’ onto the form. Move the textbox and button so that they are on the same line (next to each other) with the button on the right. Resize the textbox so that it is large enough to enter a fairly long URL. Within the Properties window, set the following values:

Text=” “

(Name)=URL

Drag and drop a ‘WebBrowser’ onto the form. Resize it and place below URL and GoButton. Within the Properties window, set the value:

(Name)=Browser

If you right-click on the form itself, you can modify its properties, including changing the background color.

Now you are ready to program. Double click the Go button. The code is now displayed with an empty function ‘GoButton_Click()’. This function will be called whenever the Go button is clicked. What we want to do is set the Browser text to the URL listed in the URL textbox. Code as follows:

this.Browser.Navigate(this.URL.Text);

Notice that as you type, you are prompted for possible extensions. This ‘IntelliSense’ feature helps you know what attributes and member functions exist for whatever object you are working with (as long as the object is predefined in your file). It serves as help and works for all the system libraries too!

Select the form design mode again by selecting the folder: “Form1.cs (Design)”. Double click on the form background. You will return to the code at the newly-created function “Form1_Load”. You may select what the browser should display as the application is started up. You may code there (please type this in yourself, do not cut and paste):

this.URL.Text = “Your Favorite URL”;

this.Browser.Navigate(this.URL.Text);

You may return to the form design mode again and double click on the URL. This automatically creates the function: URL_TextChanged(), which will be invoked whenever any key is entered. With the following code as each key is typed it will try to find the requested URL:

this.Browser.Navigate(this.URL.Text);

To compile, execute:

Build->Solution

You should see:

========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========

To run, execute:

Debug->Start Debugging

If your Browser isn’t big enough, try resizing it. Not good? Stop the debugging via:

Debug->Stop Debugging

And then try the following. Anchor each form item on the screen at its current location. Then when it resizes, it will expand or reduce in size with the window. For each control on your form set the Anchor property as follows, pressing enter for each item to ensure it records:

TextBox: Top, Left, Right

Button: Top, Right

WebBrowser: Top, Bottom, Left, Right.

Show the instructor when you are done.

Time Permitting: Add a ‘Back’ button to the form.

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download