版本:
Revit2018
VS2015
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.UI; namespace FormTest { [Transaction(TransactionMode.Manual)] [Regeneration(RegenerationOption.Manual)] public class Program : IExternalCommand { public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements) { using (Worker a = new Worker()) { a.ShowDialog(); } return Result.Succeeded; } } }
Worker.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace FormTest { public partial class Worker : Form { private delegate void SetPos(int ipos, string vinfo);//代理 public Worker() { InitializeComponent(); } private void button1_Click_1(object sender, EventArgs e) { Thread fThread = new Thread(new ThreadStart(SleepT)); fThread.Start(); } private void SleepT() { for (int i = 0; i <= 500; i++)//记得加等号,不然ProgressBar无法到100% { System.Threading.Thread.Sleep(10); SetTextMesssage(100 * i / 500, i.ToString() + "\r\n"); } } private void SetTextMesssage(int ipos, string vinfo) { if (this.InvokeRequired) { SetPos setpos = new SetPos(SetTextMesssage); this.Invoke(setpos, new object[] {ipos, vinfo}); } else { this.label1.Text = ipos.ToString() + "/1000"; //此处100不是progressBar1.Maximum this.progressBar1.Value = Convert.ToInt32(ipos); this.textBox1.AppendText(vinfo); if (progressBar1.Value == progressBar1.Maximum) { this.Close(); } } } } }
最终效果:
参考代码:
https://github.com/727175929/.net_study/tree/d1c333730ab07ce180cfa23004b8f5c51e59c8cf/C%23%E8%AF%AD%E6%B3%95%E5%AD%A6%E4%B9%A0/%E8%BF%9B%E5%BA%A6%E6%9D%A1/ProgressBar2/ProgressBar
疑问:
如何在运行完毕后,自动关闭窗体?
Kennan(https://my.csdn.net/kennan3223)回答:
让弹窗关闭的不是ProgressBar到达最大值,而是取决于你要做的业务逻辑做完了,业务逻辑结束之后,设置弹窗的DialogResult,或者直接把窗体关了 。
多线程建议使用Task和Task<T>,4.5往上建议使用async/await,对于线程的控制更舒服。