如何报告多个值?

时间:2016-10-05 08:56:21

标签: c# backgroundworker

我试图在一个DoWork中发送一个数组,但是在ReportProgress中,没有办法接收数组,我不知道我该怎么办才能传递数组,真的很感激,如果有人有任何想法。

这就是我想要做的事情:

public void backgroundWorkerXY_DoWork(object sender, DoWorkEventArgs e)
    {
        do
        {
            X = -(RSSI_PI1_ST1);
            Y = -(RSSI_PI1_ST1) + 5;
            backgroundWorkerX.ReportProgress(X,Y); // pass X and Y

            Thread.Sleep(50);
        } while (true);
    }

然后在这里传递这两个值来改变图像的位置:

    public void backgroundWorkerXY_ProgressChanged(object sender, object sender1, ProgressChangedEventArgs e)
    {
        pictureBox1.Location = new Point((int.Parse(e.ProgressPercentage.ToString())), (int.Parse(e.ProgressPercentage.ToString())) );
    // Not sure how to let a single ProgressChanged to send two values here
    }

另一种方法是将它们分开,例如,传递X,然后传递Y,但是要更改图像的位置,值必须是一个Point包含2个值(我到目前为止发现的,可能不正确),所以我假设它必须在一个ProgressChanged,

这也是我试过的

pictureBox1.Location.X = new Point((int.Parse(e.ProgressPercentage.ToString())));

然而它说 “CS1612无法修改'Control.Location'的返回值,因为它不是变量”

我要做的是改变X和Y的位置,我真的很欢迎任何替代解决方案,非常感谢任何想法或想法!

3 个答案:

答案 0 :(得分:2)

ReportProgress有一个接受任何对象的重载,你可以使用它。

worker.ReportProgress( someProgressPercentage, new Point(x,y));

private void  backgroundWorkerXY_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var point = (Point)e.UserState;
    pictureBox1.Location = point;
}

答案 1 :(得分:1)

您可以传递自定义类,例如。

public class MyCustomClass
{
    public int X {get;set;}
    public int Y {get;set;}
}

然后使用它类似于:

public void backgroundWorkerXY_DoWork(object sender, DoWorkEventArgs e)
{
    do
    {
        backgroundWorkerX.ReportProgress(
            0,
            new MyCustomClass 
            {
                X = -(RSSI_PI1_ST1),
                Y = -(RSSI_PI1_ST1) + 5
            } );

        Thread.Sleep(50);
    } while (true);
}

并像消费它一样:

public void backgroundWorkerXY_ProgressChanged(
    object sender, 
    ProgressChangedEventArgs e)
{
    var my = (MyCustomClass)e.UserState;

    pictureBox1.Location = new Point(my.X, my.Y);
}

一些参考文献:

答案 2 :(得分:1)

ReportProgress接受第二个参数为object。您可以使用它来返回自定义数据类型,或者只使用Tuple

public void backgroundWorkerXY_DoWork(object sender, DoWorkEventArgs e)
{
    do
    {
        X = -(RSSI_PI1_ST1);
        Y = -(RSSI_PI1_ST1) + 5;
        backgroundWorkerX.ReportProgress(50, new Tuple<int, int>(X,Y));

        Thread.Sleep(50);
    } while (true);
}

UserState将传递给ProgressChanged event args

public void backgroundWorkerXY_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    var args = (Tuple<int, int>)e.UserState;
    pictureBox1.Location = new Point(args.Item1, args.Item2) );
}