winform异步系统升级—BackgroundWorker

Posted 周大闯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了winform异步系统升级—BackgroundWorker相关的知识,希望对你有一定的参考价值。

BackgroundWorker用法实例

自己的代码,就是要执行的代码写到dowork里,ProgressChanged事件是控制进度时用的,最后的Completed事件进度完成,也就是dowork里的代码执行完成了

public BackgroundWorker bgWork;

bgWork = new BackgroundWorker();
bgWork.WorkerReportsProgress = true;
bgWork.DoWork += new DoWorkEventHandler(bgWork_DoWork);
bgWork.ProgressChanged += new ProgressChangedEventHandler(bgWork_ProgressChanged);
bgWork.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWork_RunWorkerCompleted);
dp = new DownLoadProgress();
dp.progressBar1.Maximum = 1000;
dp.Show();

 

void bgWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)   

      {

            try

            {

                dp.lb_dw.Visible = true;

                dp.Close();

                if (e.Error != null)

                {

                    MessageBox.Show("升级失败" + e.Error.Message);

                }

                else if (e.Result != null && e.Result.Equals(false))

                {

                   

                }

                else

                {

                    if (TZSys.Common.SysUpdate.Update.SysUpdate.PerUpdate(AppDomain.CurrentDomain.BaseDirectory + "update\\"))

                    {

                        #region 升级数据库

                        List<string> sqlstr = new List<string>();

                        string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "update\\");

                        foreach (string file in files)

                        {

                            if (file == AppDomain.CurrentDomain.BaseDirectory + "update\\"+"sql.txt")

                            {

                                using (FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "update\\sql.txt", FileMode.Open, FileAccess.Read))                                 {

                                    StreamReader sr = new StreamReader(fs);

                                    while (sr.Peek()>=0)

                                    {

                                        sqlstr.Add(sr.ReadLine());

                                    }

                                    sr.Close();

                                    fs.Close();

                                 }

                            }

                        }

                        if (sqlstr.Count > 0)

                        {

                            string datapath = AppDomain.CurrentDomain.BaseDirectory + "Data";

                            string[] directorys = Directory.GetDirectories(datapath);

                            if (directorys.Length > 0)

                            {

                                foreach (string database in directorys)

                                {

                                    string[] str = database.Split(‘\\‘);

                                    string path = database + "\\" + str[str.Length-1]+".DB";

                                    SqlOper sql = new SqlOper();

                                    sql.DealSql(path, sqlstr);

                                }

                            }

                            File.Delete(AppDomain.CurrentDomain.BaseDirectory + "update\\" + "sql.txt");

                        }

                        #endregion

                        if (TZSys.Common.SysUpdate.Update.SysUpdate.StartUpdate(AppDomain.CurrentDomain.BaseDirectory + "update\\"))

                        {

                            //保存升级后的版本号

                            XmlDocument xml = new XmlDocument();

                            xml.Load(BlackBoard.DirectoryCurrent + "XML\\update.XML");

                            if (upcmid != "" && upmainid!="")

                            {

                                xml.GetElementsByTagName("cmpid")[0].InnerText = upcmid;

                                xml.GetElementsByTagName("mainid")[0].InnerText = upmainid;

                                xml.Save(BlackBoard.DirectoryCurrent + "XML\\update.XML");

                            }

                            if (MessageBox.Show("升级成功,是否重新启动", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)

                            {

                                if (File.Exists(BlackBoard.DirectoryCurrent + "SysUpdate.dll"))

                                    File.Delete(BlackBoard.DirectoryCurrent + "SysUpdate.dll");

                                Application.Exit();

                                Process myProcess = new Process();

                                //string fileName = "ServiceClientIMForm.exe";startexe

                                string fileName = startexe;

                                ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(fileName);

                                myProcess.StartInfo = myProcessStartInfo;

                                myProcess.Start();

                                //Environment.Exit(0);

                            }

                        }

                    }

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show(ex.Message);

            }

        }

   //基本不用动

        void bgWork_ProgressChanged(object sender, ProgressChangedEventArgs e)

        {

            dp.progressBar1.Value = e.ProgressPercentage;

        }

        void bgWork_DoWork(object sender, DoWorkEventArgs e)

        {

            BackgroundWorker bw = (BackgroundWorker)sender;

            try

            {

                if (!e.Argument.ToString().Contains(".zip"))

                {

                    MessageBox.Show("更新包不是.zip文件,无法下载");

                    e.Result = false;

                }

                else if (!AppendDownLoad(e.Argument.ToString().Split(‘@‘)[0], e.Argument.ToString().Split(‘@‘)[1], bw))

                {

                    MessageBox.Show("下载失败");

                    e.Result = false;

                }

            }

            catch (Exception ex)

            {

                MessageBox.Show("下载失败" + ex.Message);

            }

        }

        //BackgroundWorker的调用方法

        public void DownloadFile(string url, string fileName)

        {

            fileName = DirPath + "\\" + fileName;

            DFileName = fileName;

            bgWork.RunWorkerAsync(url + "@" + fileName);//里面是参数是bgWork_DoWork事件的e.Argument

        }

以上是关于winform异步系统升级—BackgroundWorker的主要内容,如果未能解决你的问题,请参考以下文章

从 VS2010 升级的 VS2013 winforms 项目中缺少一些图标和文本

系统兼容性升级,同步转异步兼容升级思维转变

怎么异步显示加载中 winform

Winform/WPF async/await容易引起死锁的解决办法

Winform/WPF async/await容易引起死锁的解决办法

微信后台异步消息队列的优化升级实践分享