VS2005 new control for windows programming :BackgroundWorker

VS2005新增控件介绍:BackgroundWorker

BackgroundWorker组件:

1、使用BackgroundWorker组件时,您可以在不同于应用程序的主用户界面线程的另一线程上异步(“在后台”)执行耗时的 操作。

2、若要使用BackgroundWorker,只需要告诉该组件要在后台执行的耗时的辅助方法,然后调用RunWorkerAsync方法。

3、在辅助方法以异步方式运行的同时,您的调用线程继续正常运行。该方法运行完毕,BackgroundWorker激发RunWorkerCompleted事件(看选择包含操作结果)向调用线程发出警报。

BackgroundWorker示例:后台下载文件

using  System;
using  System.Collections.Generic;
using  System.ComponentModel;
using  System.Drawing;
using  System.Threading;
using  System.Windows.Forms;
using  System.Xml;

namespace  UseBackgroundWorker
{
    
public partial class Form1 : Form
    
{
        
private XmlDocument document = null;
        
public Form1()
        
{
            InitializeComponent();
        }


        
private void dowloadButton_Click(object sender, EventArgs e)
        
{
            
this.backgroundWorker1.RunWorkerAsync();

            
// Disable the button for the duration of the download.
            this.dowloadButton.Enabled = false;

            
// Wait for the BackgroundWorker to finish the download.
            while (this.backgroundWorker1.IsBusy)
            
{
                
// Keep UI messages moving, so the form remains 
                
// responsive during the asynchronous operation.
                Application.DoEvents();
            }


            
// The download is done, so enable the button.
            this.dowloadButton.Enabled = true;

        }


        
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        
{
            document 
= new XmlDocument();

            
// Replace this file name with a valid file name.
            document.Load(@"http://www.tailspintoys.com/sample.xml");

            
// Uncomment the following line to
            
// simulate a noticeable latency.
            
//Thread.Sleep(5000);

        }


        
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        
{
            
if (e.Error == null)
            
{
                MessageBox.Show(document.InnerXml, 
"Download Complete");
            }

            
else
            
{
                MessageBox.Show(
                    
"Failed to download file",
                    
"Download failed",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }


        }

    }

}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值