开发者

Background worker run worker completed

depending on the do work method my result could either be a List of Strings or a list of byte[]

How can we check the RunWorkerC开发者_如何学JAVAompletedEventArgs e -

if (e is List<String>)

is this the correct way to check?


No, this is not the right way.
The correct way is to use this:

if(e.Result is List<string>)
{
    //...
}
else if(e.Result is List<byte[]>)
{
    //...
}
else
{
    //...
}

e will always be of type RunWorkerCompletedEventArgs. But this class contains a property Result that contains the result of your DoWork event handler. That's the one, you need to check.


Yes, that's one possible way to do it.

If you only have two types it would be quite easy:

if(e.Result is List<string>)
{
}
else if(e.Result is List<byte[]>)
{
}
else
{
}

But the problem comes in to play if you have to support more than just two or three. In that case i'm going to create a Dictionary<Type, Action<object>> and write individual functions for each type. Something like this:

var supportedTypes = new Dictionary<Type, Action<object>>();
supportedTypes.Add(typeof(List<string>), ComputeListOfStrings);
supportedTypes.Add(typeof(List<byte[]>), ComputeListOfByteArrays);

private void ComputeListOfString(object listOfStrings)
{
    var list = (List<string>)listOfStrings;
}

private void ComputeListOfByteArrays(object listOfByteArrays)
{
    var list = (List<byte[]>)listOfByteArrays;
}

This makes it more simple to support new types and also stays to be O(1) while the if-else-if runs into the order-matters problem.

Used will this in your background worker as followed:

worker.OnRunWorkerCompleted += (sender, e) =>
{
    Action<object> supportedAction;

    supportedTypes.TryGetValue(e.Result.GetType(), out supportedAction);

    if(supportedAction != null)
    {
        supportedAction();
    }
};


the e.Result is the property with your results, so to get the type you can do:

if(e.Result.GetType().Equals(typeof(List<String>)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜