有没有办法将类的实例作为BackgroundWorker.RunWorkerAsync()的参数传递?我想这样做是为了能够访问实例的metod,然后使用此数据更新ProgressBar,显示当前进度。 稍微修改过的代码:
public class Player
{
public void Open(string file)
{
string command = "open \"" + file + "\" type MPEGVideo alias canc";
mciSendString(command, null,0,0);
}
public string Progress ()
{
StringBuilder position = new StringBuilder(200);
string command = "status canc position";
mciSendString(command, position, 200, 0);
return position.ToString();
}
public void Play()
{
string command = "play canc";
mciSendString(command, null, 0, 0);
}
}
public partial class Form1 : Form
{
Player song = new Player();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog()==DialogResult.OK)
{
song.Open(openFileDialog1.FileName);
}
}
private void button2_Click(object sender, EventArgs e)
{
song.Play();
backgroundWorker1.RunWorkerAsync(song);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
Player rola = (Player)e.Argument;
int progress
int.TryParse(rola.Progress(), out progress);
Debug.WriteLine(rola.Progress());
Debug.WriteLine(progress);
backgroundWorker1.ReportProgress(progress);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
现在代码控制台中的输出是一个空字符串和一个cero,当没有文件播放时也是如此,所以我的结论是发生了这种情况,因为BackgroundWorker没有采用Player的实例
答案 0 :(得分:0)
有没有办法将类的实例作为BackgroundWorker.RunWorkerAsync()的参数传递?
没有必要。 backgroundWorker1_DoWork
是Form1
的实例方法,因此可以直接访问song
字段。
private void button2_Click(object sender, EventArgs e)
{
song.Play();
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var worker = sender as BackgroundWorker;
// ...do something with song
// e.g.
// song.Play();
worker.ReportProgress (...);
// ...
}