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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

It is important to note that in this method (which was invoked by the DoWorkevent), you cannot directly access Windows controls because they are not thread-safe. Trying to do so will trigger a runtime error, a useful feature in Visual Studio 2008.

The ProgressChangedevent is invoked whenever the ReportProgress()method is called. In this case, you use it to update the progress bar. To generate the event handler for the ProgressChangedevent, switch to design view and look at the properties of the BackgroundWorkercomponent. In the Properties window, select the Events icon and double-click the ProgressChangedevent (see Figure 10-15).

Figure 1015 Code the event handler for the ProgressChangedevent as follows - фото 162

Figure 10-15

Code the event handler for the ProgressChangedevent as follows:

private void backgroundWorker1_ProgressChanged(

object sender, ProgressChangedEventArgs e) {

//---updates the progress bar and label control---

progressBar1.Value = e.ProgressPercentage;

lblResult.Text = e.ProgressPercentage.ToString() + "%";

}

Now double-click the RunWorkerCompletedevent to generate its event handler:

private void backgroundWorker1_RunWorkerCompleted(

object sender, RunWorkerCompletedEventArgs e) {

if (e.Error != null) MessageBox.Show(e.Error.Message);

else if (e.Cancelled) MessageBox.Show("Cancelled");

else {

lblResult.Text = "Sum of 1 to " + txtNum.Text + " is " + e.Result;

}

btnStart.Enabled = true;

btnCancel.Enabled = false;

}

The RunWorkerCompletedevent is fired when the thread ( SumNumbers(), in this case) has completed running. Here you print the result accordingly.

Finally, when the user clicks the Cancel button, you cancel the process by calling the CancelAsync()method:

private void btnCancel_Click(object sender, EventArgs e) {

//---Cancel the asynchronous operation---

backgroundWorker1.CancelAsync();

btnCancel.Enabled = false;

}

Testing the Application

To test the application, press F5, enter a large number (say, 9999999), and click the Start button. The progress bar updating should begin updating. When the process is complete, the result is printed in the Labelcontrol (see Figure 10-16).

Figure 1016 Summary This chapter explains the rationale for threading and - фото 163

Figure 10-16

Summary

This chapter explains the rationale for threading and how it can improve the responsiveness of your applications. Threading is a complex topic and you need to plan carefully before using threads in your application. For instance, you must identify the critical regions so that you can ensure that the different threads accessing the critical region are synchronized. Finally, you saw that Windows Forms controls are not thread-safe and that you need to use delegates when updating UI controls from another thread.

Chapter 11

Files and Streams

At some stage in your development cycle, you need to store data on some persistent media so that when the computer is restarted the data is still be available. In most cases, you either store the data in a database or in files. A file is basically a sequence of characters stored on storage media such as your hard disks, thumb drives, and so on. When you talk about files, you need to understand another associated term — streams. A stream is a channel in which data is passed from one point to another. In .NET, streams are divided into various types: file streams for files held on permanent storage, network streams for data transferred across the network, memory streams for data stored in internal storage, and so forth.

With streams, you can perform a wide range of tasks, including compressing and decompressing data, serializing and deserializing data, and encrypting and decrypting data. This chapter examines:

□ Manipulating files and directories

□ How to quickly read and write data to files

□ The concepts of streams

□ Using the BufferedStreamclass to improve the performance of applications reading from a stream

□ Using the FileStreamclass to read and write to files

□ Using the MemoryStreamclass to use the internal memory store as a buffer

□ Using the NetworkStreamclass for network programming

□ The various types of cryptographic classes available in .NET

□ Performing compressions and decompression on streams

□ Serializing and deserializing objects into binary and XML data

Working with Files and Directories

The System.IOnamespace in the .NET Framework contains a wealth of classes that allow synchronous and asynchronous reading and writing of data on streams and files. In the following sections, you will explore the various classes for dealing with files and directories.

Remember to import the System.IOnamespace when using the various classes in the System.IOnamespace.

Working with Directories

The .NET Framework class library provides two classes for manipulating directories:

DirectoryInfoclass

Directoryclass

The DirectoryInfoclass exposes instance methods for dealing with directories while the Directoryclass exposes static methods.

DirectoryInfo Class

The DirectoryInfoclass provides various instance methods and properties for creating, deleting, and manipulating directories. The following table describes some of the common methods you can use to programmatically manipulate directories.

Method Description
Create Creates a directory.
CreateSubdirectory Creates a subdirectory.
Delete Deletes a directory.
GetDirectories Gets the subdirectories of the current directory.
GetFiles Gets the file list from a directory.

And here are some of the common properties:

Properties Description
Exists Indicates if a directory exists.
Parent Gets the parent of the current directory.
FullName Gets the full path name of the directory.
CreationTime Gets or sets the creation time of current directory.

Refer to the MSDN documentation for a full list of methods and properties.

To see how to use the DirectoryInfoclass, consider the following example:

static void Main(string[] args) {

string path = @"C:\My Folder";

DirectoryInfo di = new DirectoryInfo(path);

try {

//---if directory does not exists---

if (!di.Exists) {

//---create the directory---

di.Create(); //---c:\My Folder---

//---creates subdirectories---

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

Интервал:

Закладка:

Сделать

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

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


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

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

x