作为BackgroundWorker参数

时间:2017-11-11 01:46:27

标签: c# visual-studio arguments

有没有办法将类的实例作为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的实例

1 个答案:

答案 0 :(得分:0)

  

有没有办法将类的实例作为BackgroundWorker.RunWorkerAsync()的参数传递?

没有必要。 backgroundWorker1_DoWorkForm1的实例方法,因此可以直接访问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 (...);
     // ...
}