异步编程入门指南
立即解锁
发布时间: 2025-08-21 00:06:09 阅读量: 2 订阅数: 8 


C#编程基础与实战技巧
### 异步编程入门指南
#### 1. BackgroundWorker 类的使用
BackgroundWorker 类虽为 GUI 编程设计,但我们先通过控制台程序来了解它。此程序会创建一个后台线程对一系列数字求和,过程中会多次检查是否被取消。若被取消,会清理并退出;若完成,会将总和存储在 Result 字段后退出。同时,主线程也会对自己的数字序列求和,并报告自身总和以及后台线程的结果。
以下是完整代码:
```csharp
using System;
using System.ComponentModel; // Must have this namespace
using System.Threading; // Must have this namespace
namespace ConsoleBackgroundWorker
{
class DoBackgroundwork
{
BackgroundWorker bgWorker = new BackgroundWorker();
public long BackgroundTotal { get; private set; }
public bool CompletedNormally { get; private set; }
// Constructor
public DoBackgroundwork()
{
// Set BackgroundWorker properties
bgWorker.WorkerReportsProgress = true;
bgWorker.WorkerSupportsCancellation = true;
// Connect handlers to BackgroundWorker object.
bgWorker.DoWork += DoWork_Handler;
bgWorker.ProgressChanged += ProgressChanged_Handler;
bgWorker.RunWorkerCompleted += RunWorkerCompleted_Handler;
}
public void StartWorker()
{
if ( !bgWorker.IsBusy )
bgWorker.RunWorkerAsync();
}
// This just calculates the sum of the integers from 0 to the input value.
public static long CalculateTheSequence( long value )
{
long total = 0;
for ( int i=0; i < value; i++ )
total += i;
return total;
}
public void DoWork_Handler( object sender, DoWorkEventArgs args )
{
BackgroundWorker worker = sender as BackgroundWorker;
// Do the background calculation
long total = 0;
for ( int i = 1; i <= 5; i++ )
{
// Each time through the loop, check to see if we've been cancelled
if ( worker.CancellationPending )
{
args.Cancel = true;
worker.ReportProgress( -1 );
break;
}
else
{
// If we haven't been cancelled, then continue the calculation.
total += CalculateTheSequence( i * 10000000 );
worker.ReportProgress( i * 20 );
// Slow the program down to a more comfortable output rate
// just for this demo.
Thread.Sleep( 300 );
}
}
args.Result = total; // Store the result and exit.
}
// Handle input from background thread.
private void ProgressChanged_Handler
( object sender, ProgressChangedEventArgs args )
{
string output
= args.ProgressPercentage == -1
? " Cancelled"
: string.Format(" {0}%", args.ProgressPercentage );
Console.WriteLine( output );
}
// On completion of background thread, summarize and store the result.
private void RunWorkerCompleted_Handler
( object sender, RunWorkerCompletedEventArgs args )
{
CompletedNormally = !args.Cancelled;
BackgroundTotal = args.Cancelled
? 0
: (long) args.Result; // Cast from object
}
public void Cancel()
{
if( bgWorker.IsBusy )
bgWorker.CancelAsync();
}
}
class Program
{
static void Main()
{
GiveInstructionsToTheUser();
OutputTheSummaryHeaders();
// Create and Start the background worker
DoBackgroundwork bgw = new DoBackgroundwork();
bgw.StartWorker();
// Start the computation on the main thread. Each time through the loop,
// check to see whether the user has cancelled the background thread.
// After the calculation, add a short sleep, just to slow the program
// down enough so the main thread doesn't run faster than the background.
long mainTotal = 0;
for ( int i = 0; i < 5; i++ )
{
if ( Program.CheckForCancelInput() )
```
0
0
复制全文
相关推荐









