Silverlight多线程与网络编程实战
立即解锁
发布时间: 2025-08-26 01:20:41 阅读量: 5 订阅数: 13 

### Silverlight 多线程与网络编程实战
#### 多线程中的取消支持
在多线程编程中,为线程添加取消功能是很有必要的。为了实现取消功能,线程包装器需要一个字段来指示是否需要停止处理。以下是添加到 `ThreadWrapperBase` 中的代码:
```csharp
// Flag that indicates a stop is requested.
private bool cancelRequested = false;
protected bool CancelRequested
{
get { return cancelRequested; }
}
// Call this to request a cancel.
public void RequestCancel()
{
cancelRequested = true;
}
// When cancelling, the worker should call the OnCancelled() method
// to raise the Cancelled event.
public event EventHandler Cancelled;
protected void OnCancelled()
{
if (Cancelled != null)
Cancelled(this, EventArgs.Empty);
}
```
在 `FindPrimesThreadWrapper.DoWork()` 方法中,需要定期检查是否有取消请求:
```csharp
int iteration = list.Length / 100;
if (i % iteration == 0)
{
if (CancelRequested)
{
return;
}
}
```
同时,需要修改 `ThreadWrapperBase.StartTaskAsync()` 方法,以识别操作结束的两种可能方式:
```csharp
private void StartTaskAsync()
{
DoTask();
if (CancelRequested)
{
status = StatusState.Cancelled;
OnCancelled();
}
else
{
status = StatusState.Completed;
OnCompleted();
}
}
```
要使用取消功能,只需为 `Cancelled` 事件添加事件处理程序,并添加一个取消按钮。以下是取消请求的代码:
```csharp
private void cmdCancel_Click(object sender, RoutedEventArgs e)
{
threadWrapper.RequestCancel();
}
```
取消完成后的事件处理程序:
```csharp
private void threadWrapper_Cancelled(object sender, EventArgs e)
{
this.Dispatcher.BeginInvoke(delegate() {
lblStatus.Text = "Search cancelled.";
cmdFind.IsEnabled = true;
cmdCancel.IsEnabled = false;
});
}
```
需要注意的是,Silverlight 线程不能使用 `Abort()` 方法停止,只能请求礼貌停止。
#### BackgroundWorker 组件
`BackgroundWorker` 是一种简单而安全的多线程方法,它在 .NET 2.0 中首次引入,用于简化 Windows Forms 应用程序中的线程处理。在 Silverlight 中同样适用。
##### 创建 BackgroundWorker
要使用 `BackgroundWorker`,首先需要创建一个实例,并以编程方式附加事件处理程序。以下是初始化代码:
```csharp
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public BackgroundWorkerTest()
{
InitializeComponent();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
backgroundWorker.DoWork += backgroundWorker_DoWork;
backgroundWorker.ProgressChanged += backgroundWorker_ProgressChanged;
backgroundWorker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted;
}
```
##### 运行 BackgroundWorker
以质数搜索为例,首先需要创建一个自定义类来传递输入参数:
```csharp
public class FindPrimesInput
{
public int From { get; set; }
public int To { get; set; }
public FindPrimesInput(int from, int to)
{
From = from;
To = to;
}
}
```
当用户点击查找质数按钮时,启动 `BackgroundWorker`:
```csharp
private void cmdFind_Click(object sender, RoutedEventArgs e)
{
// Disable this button and clear previous results.
cmdFind.IsEnabled = false;
cmdCancel.IsEnabled = true;
lstPrimes.Items.Clear();
// Get the search range.
int from, to;
if (!Int32.TryParse(txtFrom.Text, out from))
{
MessageBox.Show("Invalid From value.");
return;
}
if (!Int32.TryParse(txtTo.Text, out to))
{
MessageBox.Show("Invalid To value.");
return;
}
// Start the search for primes on another thread.
FindPrimesInput input = new FindPrimesInput(from, to);
backgroundWorker.RunWorkerAsync(input);
}
```
`BackgroundWorker` 开始执行时,会触发 `DoWork` 事件:
```csharp
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// Get the input values.
FindPrimesInput input = (FindPrimesInput)e.Argument;
// Start the search for primes and wait.
// This is the time-consuming part, but it won't freeze the
// user interface because it takes place on another thread.
int[] pri
```
0
0
复制全文
相关推荐









