我創建了一個Windows窗體程序,用於分解文件並將其組件發送到服務器。這些文件很大,所以我創建了一個progressBar,因此用戶不會在事務發生時凍結它。我想要做的是有一些機制,只有當所有線程完成而不會阻塞UI線程時纔會主動觸發(再次,因此平臺不會認爲它被凍結)。我能想到的最好的方式是被動地「等到真實」,但我覺得必須有更好的方式來做到這一點。我嘗試過嘗試創建一個事件或回調,但老實說,我剛剛結束時比我開始時更困惑。下面是我現在怎麼做這樣一個例子:如何在進度條完成時觸發事件
public partial class Program : Form
{
private readonly OpenFileDialog _ofd = new OpenFileDialog();
public delegate void BarDelegate();
private string _path;
private void button1_Click(object sender, EventArgs e)
{
if (_ofd.ShowDialog() != DialogResult.OK) return;
textBox1.Text = _ofd.SafeFileName;
_path = _ofd.FileName;
}
private void button2_Click(object sender, EventArgs e)
{
var allLinesFromFile = File.ReadAllLines(_path);
progressBar1.Minimum = 0;
progressBar1.Maximum = allLinesFromFile.Length;
Task.Factory.StartNew(() => Parallel.ForEach(allLinesFromFile, DoSomething));
while (progressBar1.Value < progressBar1.Maximum) //there has to be a better way to do this...
{
MessageBox.Show("Please wait.", "Record Poster", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
}
//some processes here which should only take place after all threads are complete.
var postingComplete = MessageBox.Show("The posting is complete!", "Record Poster", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
if (postingComplete == DialogResult.OK) Environment.Exit(0);
}
private void DoSomething(string record)
{
//some string manipulation and server transactions here
BeginInvoke(new BarDelegate(() => progressBar1.Increment(1)));
}
}
你是爲進度條提供價值的人 - 所以當你達到100時,請調用你想做的方法。首先,你不需要TaskFactory。 –
第三 - 有多少條線?看起來像顯示一個消息框會比處理本身花費更多的時間 –
您可以編寫'ValueChanged'事件並檢查'Value == Maximum' – TaW