sp;Content="从1到100累加" Click="OnRun" Margin="10" />
<Button x:Name="btnCancel" Content="取 消" Click="OnCancel" Margin="10" />
</StackPanel>
</Grid>
接下来就是相应的cs代码了,相当的注释我已写入代码段中,相信大家看一下就会明白了:)
另外还需要在cs文件中引用一下相应的名空间如下:
现在就可以编译运行这个silverlight应用的(之前请先运行上面的wcf项目).
public partial class Page : UserControl
{
private System.ComponentModel.BackgroundWorker worker;
private int sum = 0;//累加数
private int cur_number = 1;//当前数值
void OnRun(object sender, EventArgs args)
{
worker = new System.ComponentModel.BackgroundWorker();
//当前BackgroundWorker所执行的操作
worker.DoWork += OnDoWork;
//绑定异步操作进度的事件
worker.ProgressChanged += OnProgressChanged;
//绑定操作成功完成的处理事件
worker.RunWorkerCompleted += OnWorkCompleted;
//是否报告进度更新
worker.WorkerReportsProgress = true;
//是否支持异步取消
worker.WorkerSupportsCancellation = true;
//开始执行后台操作
worker.RunWorkerAsync();
}
void OnWorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
Exception ex = e.Error; //int x = 10;
}
if (e.Cancelled)
{