我有一个简单的程序,可以将文件并行复制到多个位置。我有一个作为进度条弹出的表单:
public partial class PleaseWait : Form
{
private static PleaseWait mInstance;
public static void Create()
{
var t = new System.Threading.Thread(() =>
{
mInstance = new PleaseWait();
mInstance.FormClosed += (s, e) => mInstance = null;
Application.Run(mInstance);
});
t.SetApartmentState(System.Threading.ApartmentState.STA);
t.IsBackground = true;
t.Start();
}
public static void Destroy()
{
if (mInstance != null) mInstance.Invoke(new Action(() => mInstance.Close()));
}
public PleaseWait()
{
InitializeComponent();
}
public int t = 0;
private void timer1_Tick(object sender, EventArgs e)
{
if (t == 100)
{
t = 0;
}
else
{
t = t + 10;
progressBar1.Value = t;
}
}
}
我Create
为每个复制线程调用,然后在每个完成 9 次(10 次)后销毁,它将全部关闭,但有时我仍然打开一个,所以我尝试使用此代码
private void closewait()
{
foreach (Form f in Application.OpenForms)
{
if (f is file_copy.PleaseWait)
{
f.Dispose();
}
}
}
但我得到一个跨线程错误。我如何确保副本完成后我没有任何PleaseWait
打开的表格。