如何:在后台运行操作

来源:互联网 发布:域名主机代理 编辑:程序博客网 时间:2024/04/30 07:23
Windows 窗体编程
如何:在后台运行操作

 

如果有一个需要很长时间才能完成的操作,而且不希望用户界面中出现延迟,则可以使用 BackgroundWorker 类来在另一个线程上运行该操作。

下面的代码示例演示如何在后台运行耗时的操作。该窗体具有“开始”和“取消”按钮。单击“开始”按钮可运行异步操作。单击“取消”按钮可停止正在运行的异步操作。每个操作的结果均在 MessageBox 中显示。

Visual Studio 中对此任务提供了广泛的支持。

有关更多信息,请参见演练:在后台运行操作。

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

namespace BackgroundWorkerExample
{
    
public class Form1 : Form
    
{
        
public Form1()
        
{
            InitializeComponent();
        }


        
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        
{
            
// Do not access the form's BackgroundWorker reference directly.
            
// Instead, use the reference provided by the sender parameter.
            BackgroundWorker bw = sender as BackgroundWorker;

            
// Extract the argument.
            int arg = (int)e.Argument;

            
// Start the time-consuming operation.
            e.Result = TimeConsumingOperation(bw, arg);

            
// If the operation was canceled by the user, 
            
// set the DoWorkEventArgs.Cancel property to true.
            if (bw.CancellationPending)
            
{
                e.Cancel 
= true;
            }

        }


        
// This event handler demonstrates how to interpret 
        
// the outcome of the asynchronous operation implemented
        
// in the DoWork event handler.
        private void backgroundWorker1_RunWorkerCompleted(
            
object sender, 
            RunWorkerCompletedEventArgs e)
        
{   
            
if (e.Cancelled)
            
{
                
// The user canceled the operation.
                MessageBox.Show("Operation was canceled");
            }

            
else if (e.Error != null)
            
{
                
// There was an error during the operation.
                string msg = String.Format("An error occurred: {0}", e.Error.Message);
                MessageBox.Show(msg);
            }

            
else
            
{
                
// The operation completed normally.
                string msg = String.Format("Result = {0}", e.Result);
                MessageBox.Show(msg);
            }

        }


        
// This method models an operation that may take a long time 
        
// to run. It can be cancelled, it can raise an exception,
        
// or it can exit normally and return a result. These outcomes
        
// are chosen randomly.
        private int TimeConsumingOperation( 
            BackgroundWorker bw, 
            
int sleepPeriod )
        
{
            
int result = 0;

            Random rand 
= new Random();

            
while (!this.backgroundWorker1.CancellationPending)
            
{
                
bool exit = false;

                
switch (rand.Next(3))
                
{
                    
// Raise an exception.
                    case 0:
                    
{
                        
throw new Exception("An error condition occurred.");
                        
break;
                    }


                    
// Sleep for the number of milliseconds
                    
// specified by the sleepPeriod parameter.
                    case 1:
                    
{
                        Thread.Sleep(sleepPeriod);
                        
break;
                    }


                    
// Exit and return normally.
                    case 2:
                    
{
                        result 
= 23;
                        exit 
= true;
                        
break;
                    }


                    
default:
                    
{
                        
break;
                    }

                }


                
if( exit )
                
{
                    
break;
                }

            }


            
return result;
        }


        
private void startBtn_Click(object sender, EventArgs e)
        
{
            
this.backgroundWorker1.RunWorkerAsync(2000);
        }


        
private void cancelBtn_Click(object sender, EventArgs e)
        
{
            
this.backgroundWorker1.CancelAsync();
        }


        
/// <summary>
        
/// Required designer variable.
        
/// </summary>

        private System.ComponentModel.IContainer components = null;

        
/// <summary>
        
/// Clean up any resources being used.
        
/// </summary>
        
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>

        protected override void Dispose(bool disposing)
        
{
            
if (disposing && (components != null))
            
{
                components.Dispose();
            }

            
base.Dispose(disposing);
        }


        
Windows Form Designer generated code

        
private System.ComponentModel.BackgroundWorker backgroundWorker1;
        
private System.Windows.Forms.Button startBtn;
        
private System.Windows.Forms.Button cancelBtn;
    }


    
public class Program
    
{
        
private Program()
        
{
        }


        
/// <summary>
        
/// The main entry point for the application.
        
/// </summary>

        [STAThread]
        
static void Main()
        
{
            Application.EnableVisualStyles();
            Application.Run(
new Form1());
        }

    }

}
 
原创粉丝点击