私はこのような問題があります:C#Winform ProgressBarとBackgroundWorker
私はMainFormという名前のフォームを持っています。私はこのフォーム上で行われるべき長い操作を持っています。
この長い操作が行われている間、私はMainFormの上に名前付きProgressFormから別のものを表示する必要があります。
プログレスフォームには進行状況バーがあります。長い操作が行われている間は更新が必要です。
ロング操作が完了したら、ProgressFormを自動的に閉じます。
私は、次のようないくつかのコードを書かれている:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ClassLibrary
{
public class MyClass
{
public static string LongOperation()
{
Thread.Sleep(new TimeSpan(0,0,30));
return "HelloWorld";
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace BackgroungWorker__HelloWorld
{
public partial class ProgressForm : Form
{
public ProgressForm()
{
InitializeComponent();
}
public ProgressBar ProgressBar
{
get { return this.progressBar1; }
set { this.progressBar1 = value; }
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ClassLibrary;
namespace BackgroungWorker__HelloWorld
{
public partial class MainForm : Form
{
ProgressForm f = new ProgressForm();
public MainForm()
{
InitializeComponent();
}
int count = 0;
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (f != null)
{
f.ProgressBar.Value = e.ProgressPercentage;
}
++count;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
MessageBox.Show("The task has been cancelled");
}
else if (e.Error != null)
{
MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
}
else
{
MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
if (f == null)
{
f = new ProgressForm();
}
f.ShowDialog();
//backgroundWorker1.ReportProgress(100);
MyClass.LongOperation();
f.Close();
}
private void btnStart_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
backgroundWorker1.CancelAsync();
this.Close();
}
}
}
私はプログレスバーを更新するための方法を見つけることではないのです。
私はbackgroundWorker1.ReportProgress()
をどこに置くべきですか、どうすればいいですか?
MyClassに変更を加えてはいけません。私のアプリケーションのこの層で何が起こるか、またはどれくらいの時間がかかるかはわかりません。
誰でも手伝ってもらえますか?
MyClassに変更を加えてはいけません。 Coz、私は私のアプリのこの層で何が起こるかわからない。 – anonymous
その後、進捗状況を正確に報告することはできません。つまり、ProgressFormにタイマーを追加して毎秒プログレスバーを増やすことができますが、それは幻影に過ぎません。 *実際の進捗状況を知る方法がない場合は、プログレスバーはどれくらい便利ですか? –