简体   繁体   中英

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 RunWorkerCompletedEventArgs e -

if (e is List<String>)

is this the correct way 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();
    }
};

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.

e.Result是您的结果的属性,因此要获得您可以执行的类型:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM