Wei-Meng Lee - C# 2008 Programmer's Reference

Здесь есть возможность читать онлайн «Wei-Meng Lee - C# 2008 Programmer's Reference» весь текст электронной книги совершенно бесплатно (целиком полную версию без сокращений). В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Город: Indianapolis, Год выпуска: 2009, ISBN: 2009, Издательство: Wiley Publishing, Inc., Жанр: Программирование, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

C# 2008 Programmer's Reference: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «C# 2008 Programmer's Reference»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

C# 2008 Programmers Reference provides a concise and thorough reference on all aspects of the language. Each chapter contains detailed code samples that provide a quick and easy way to understand the key concepts covered.

C# 2008 Programmer's Reference — читать онлайн бесплатно полную книгу (весь текст) целиком

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «C# 2008 Programmer's Reference», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать
Figure 107 To resolve this you call the Pulsemethod of the Monitorclass in - фото 154

Figure 10-7

To resolve this, you call the Pulse()method of the Monitorclass in the credit thread so that it can send a signal to the waiting thread that the lock is now released and is now going to pass back to it. The modified code for the Credit()function now looks like this:

static void Credit() {

//---credit 1500---

for (int i = 0; i < 15; i++) {

Monitor.Enter(obj);

balance += 100;

if (balance < 0) Monitor.Pulse(obj);

Console.WriteLine("After crediting, balance is {0}", balance);

Monitor.Exit(obj);

}

}

Figure 10-8 shows that the sequence now is correct.

Figure 108 The complete program is as follows class Program used - фото 155

Figure 10-8

The complete program is as follows:

class Program {

//---used for locking---

static object obj = new object();

//---initial balance amount---

static int balance = 500;

static void Main(string[] args) {

Thread t1 = new Thread(new ThreadStart(Debit));

t1.Start();

Thread t2 = new Thread(new ThreadStart(Credit));

t2.Start();

Console.ReadLine();

}

static void Credit() {

//---credit 1500---

for (int i = 0; i < 15; i++) {

Monitor.Enter(obj);

balance += 100;

if (balance > 0) Monitor.Pulse(obj);

Console.WriteLine("After crediting, balance is {0}", balance);

Monitor.Exit(obj);

}

}

static void Debit() {

//---debit 1000---

for (int i = 0; i < 10; i++) {

Monitor.Enter(obj);

if (balance == 0) Monitor.Wait(obj);

balance -= 100;

Console.WriteLine("After debiting, balance is {0}", balance);

Monitor.Exit(obj);

}

}

}

Thread Safety in Windows Forms

One of the common problems faced by Windows programmers is the issue of updating the UI in multithreaded situations. To improve the efficiency of their applications, Windows developers often use threads to perform different tasks in parallel. One thread may be consuming a Web Service, another performing file I/O, another doing some mathematical calculations, and so on. As each thread completes, the developers may want to display the result on the Windows form itself.

However, it is important to know that controls in Windows Forms are bound to a specific thread and are thus not thread safe; this means that if you are updating a control from another thread, you should not call the control's member directly. Figure 10-9 shows the conceptual illustration.

Figure 109 To update a Windows Forms control from another thread use a - фото 156

Figure 10-9

To update a Windows Forms control from another thread, use a combination of the following members of that particular control:

InvokeRequired property— Returns a Boolean value indicating if the caller must use the Invoke()method when making call to the control if the caller is on a different thread than the control. The InvokeRequiredproperty returns trueif the calling thread is not the thread that created the control or if the window handle has not yet been created for that control.

Invoke() method— Executes a delegate on the thread that owns the control's underlying windows handle.

BeginInvoke() method— Calls the Invoke()method asynchronously.

EndInvoke() method— Retrieves the return value of the asynchronous operation started by the BeginInvoke()method.

To see how to use these members, create a Windows application project in Visual Studio 2008. In the default Form1, drag and drop a Labelcontrol onto the form and use its default name of Label1. Figure 10-10 shows the control on the form.

Figure 1010 Doubleclick the form to switch to its codebehind The - фото 157

Figure 10-10

Double-click the form to switch to its code-behind. The Form1_Loadevent handler is automatically created for you.

Add the following highlighted code:

private void Form1_Load(object sender, EventArgs e) {

if (label1.InvokeRequired) {

MessageBox.Show("Need to use Invoke()");

} else {

MessageBox.Show("No need to use Invoke()");

}

}

This code checks the InvokeRequiredproperty to determine whether you need to call Invoke()if you want to call the Labelcontrol's members. Because the code is in the same thread as the Labelcontrol, the value for the InvokeRequiredproperty would be falseand the message box will print the message No need to use Invoke().

Now to write some code to display the current time on the Label control and to update the time every second, making it look like a clock. Define the PrintTime() function as follows:

private void PrintTime() {

try {

while (true) {

if (label1.InvokeRequired) {

label1.Invoke(myDelegate, new object[] {

label1, DateTime.Now.ToString()

});

Thread.Sleep(1000);

} else label1.Text = DateTime.Now.ToString();

}

} catch (Exception ex) {

Console.WriteLine(ex.Message);

}

}

Because the PrintTime()function is going to be executed on a separate thread (you will see this later), you need to use the Invoke()method to call a delegate ( myDelegate, which you will define shortly) so that the time can be displayed in the Label control. You also insert a delay of one second so that the time is refreshed every second.

Define the updateLabelfunction so that you can set the Label's control Textproperty to a specific string:

private void updateLabel(Control ctrl, string str) {

ctrl.Text = str;

}

This function takes in two parameters — the control to update, and the string to display in the control. Because this function resides in the UI thread, it cannot be called directly from the PrintTime()function; instead, you need to use a delegate to point to it. So the next step is to define a delegate type for this function and then create the delegate:

public partial class Form1 : Form {

//---delegate type for the updateLabel() function---

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «C# 2008 Programmer's Reference»

Представляем Вашему вниманию похожие книги на «C# 2008 Programmer's Reference» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Отзывы о книге «C# 2008 Programmer's Reference»

Обсуждение, отзывы о книге «C# 2008 Programmer's Reference» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x