Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
57
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

// Wait for TimeintensiveMethod to complete and get its result int x = await task;

Console.WriteLine("Count: " + x);

}

private async Task<int> TimeintensiveMethod(object file)

{

Console.WriteLine("Start TimeintensiveMethod.");

// Do some time intensive calculations...

using (StreamReader reader = new StreamReader(file.ToString()))

{

string s = await reader.ReadToEndAsync();

for (int i = 0; i < 10000; i++) s.GetHashCode();

}

Console.WriteLine("End TimeintensiveMethod.");

// return something as a "result" return new Random().Next(100);

}

Section 113.4: BackgroundWorker

See below for a simple example of how to use a BackgroundWorker object to perform time-intensive operations in a background thread.

You need to:

1.Define a worker method that does the time-intensive work and call it from an event handler for the DoWork event of a BackgroundWorker.

2.Start the execution with RunWorkerAsync. Any argument required by the worker method attached to DoWork can be passed in via the DoWorkEventArgs parameter to RunWorkerAsync.

In addition to the DoWork event the BackgroundWorker class also defines two events that should be used for interacting with the user interface. These are optional.

The RunWorkerCompleted event is triggered when the DoWork handlers have completed.

The ProgressChanged event is triggered when the ReportProgress method is called.

public void ProcessDataAsync()

{

//Start the time intensive method

BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += BwDoWork;

bw.RunWorkerCompleted += BwRunWorkerCompleted; bw.RunWorkerAsync(@"PATH_TO_SOME_FILE");

//Control returns here before TimeintensiveMethod returns

Console.WriteLine("You can read this while TimeintensiveMethod is still running.");

}

// Method that will be called after BwDoWork exits

private void BwRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)

{

// we can access possible return values of our Method via the Parameter e

Console.WriteLine("Count: " + e.Result);

}

GoalKicker.com – C# Notes for Professionals

581

// execution of our time intensive Method

private void BwDoWork(object sender, DoWorkEventArgs e)

{

e.Result = TimeintensiveMethod(e.Argument);

}

private int TimeintensiveMethod(object file)

{

Console.WriteLine("Start TimeintensiveMethod.");

// Do some time intensive calculations...

using (StreamReader reader = new StreamReader(file.ToString()))

{

string s = reader.ReadToEnd();

for (int i = 0; i < 10000; i++) s.GetHashCode();

}

Console.WriteLine("End TimeintensiveMethod.");

// return something as a "result" return new Random().Next(100);

}

Section 113.5: Task

See below for a simple example of how to use a Task to do some time intensive stu in a background process. All you need to do is wrap your time intensive method in a Task.Run() call.

public void ProcessDataAsync()

{

// Start the time intensive method

Task<int> t = Task.Run(() => TimeintensiveMethod(@"PATH_TO_SOME_FILE"));

// Control returns here before TimeintensiveMethod returns

Console.WriteLine("You can read this while TimeintensiveMethod is still running.");

Console.WriteLine("Count: " + t.Result);

}

private int TimeintensiveMethod(object file)

{

Console.WriteLine("Start TimeintensiveMethod.");

// Do some time intensive calculations...

using (StreamReader reader = new StreamReader(file.ToString()))

{

string s = reader.ReadToEnd();

for (int i = 0; i < 10000; i++) s.GetHashCode();

}

Console.WriteLine("End TimeintensiveMethod.");

// return something as a "result" return new Random().Next(100);

}

GoalKicker.com – C# Notes for Professionals

582

Section 113.6: Thread

See below for a simple example of how to use a Thread to do some time intensive stu in a background process.

public async void ProcessDataAsync()

{

// Start the time intensive method

Thread t = new Thread(TimeintensiveMethod);

// Control returns here before TimeintensiveMethod returns

Console.WriteLine("You can read this while TimeintensiveMethod is still running.");

}

private void TimeintensiveMethod()

{

Console.WriteLine("Start TimeintensiveMethod.");

// Do some time intensive calculations...

using (StreamReader reader = new StreamReader(@"PATH_TO_SOME_FILE"))

{

string v = reader.ReadToEnd();

for (int i = 0; i < 10000; i++) v.GetHashCode();

}

Console.WriteLine("End TimeintensiveMethod.");

}

As you can see we can not return a value from our TimeIntensiveMethod because Thread expects a void Method as its parameter.

To get a return value from a Thread use either an event or the following:

int ret;

Thread t= new Thread(() =>

{

Console.WriteLine("Start TimeintensiveMethod.");

// Do some time intensive calculations...

using (StreamReader reader = new StreamReader(file))

{

string s = reader.ReadToEnd();

for (int i = 0; i < 10000; i++) s.GetHashCode();

}

Console.WriteLine("End TimeintensiveMethod.");

// return something to demonstrate the coolness of await-async ret = new Random().Next(100);

});

t.Start(); t.Join(1000);

Console.Writeline("Count: " + ret);

GoalKicker.com – C# Notes for Professionals

583