Setting RunWorkerCompleted value

ε祈祈猫儿з 提交于 2019-12-11 07:49:49

问题


If i have a background worker that does some tasks in its do work

    String val= getVal("Val");
    byte[] b = (byte[])e.Argument;

    b = getData.FromPlace(val);

How do i pass the vakue of b to the runworkercompleted method?


回答1:


You could use closure

void Main()
{

    var bw = new BackgroundWorker();

    byte[] b;

    bw.DoWork += (sender, args) => {

        b = DoStuff();
    };
}

byte[] DoStuff() {

    String val= getVal("Val");
    byte[] b = (byte[])e.Argument;

    b = getData.FromPlace(val);

    return b;
}

You could also use return Result property on the event args object. I think this way gives more flexibility.

void Main()
{
    var bw = new BackgroundWorker();

    bw.DoWork += (sender, args) => {

        args.Result = DoStuff();
    };

    bw.RunWorkerCompleted += (sender, args) =>  {
        var result = args.Result as byte[];
    };

    bw.RunWorkerAsync();
}

byte[] DoStuff() {
    return new byte[10];
}



回答2:


You can use an instance variable. Place the declaration above the DoWork event definition.

private byte[] b;


来源:https://stackoverflow.com/questions/5499657/setting-runworkercompleted-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!