Mike Marks
Mike Marks

Reputation: 10139

System.Timers - how to pass a variable into the ElapsedEvent that changes through each "foreach" iteration

I'll try to keep this as simple as possible. Here's my method, just to start - and I understand the below code is incorrect - this is just what I have at the moment:

public static void GetActorsFromCastList(TmdbMovieCast cast)
{
    // use timers here
    List<Cast> liCast = cast.cast;

    Timer actorTimer = new Timer(1000);

    // put the below into a foreach loop to get a new personId each time???

    foreach (var i in liCast)
    {
        actorTimer.Elapsed += new ElapsedEventHandler((sender, e) => RunActorEvent(sender, e, i.id));
        actorTimer.Start();
    }
}

public static void RunActorEvent(object sender, ElapsedEventArgs e, int personId)
{
    // run a single API call here to get a Person (actor)
    _actors.Add(_api.GetPersonInfo(personId));
}

As you can see, I created a System.Timer that, as designed above, the idea is to call the RunActorEvent every second and pass in a different PersonId each time. The end goal is to call the RunActorEvent one time each second, but each time pass in a new PersonId. I already created the ElapsedEventHandler such that I added a third parameter PersonId.

That's where I'm at. The dilemma I'm having is this just doesn't look correct. I mean, I have a foreach loop that essentially creates a new ElapsedEventHander through each iteration, and I don't think this should be the design.

QUESTION: How do I create a System.Timer and a corresponding ElapsedEventHandler but pass in a new variable (PersonId) into RunActorEvent (the Event Handler) each time the ElapsedEventHander is called?

Upvotes: 0

Views: 267

Answers (2)

tnw
tnw

Reputation: 13877

Just another way of writing it which, in my opinion, is a bit cleaner...

actorTimer.Elapsed += (sender, e) => RunActorEvent(sender, e, personId);

Unrelated to your question, but this line hurts:

List<Cast> liCast = cast.cast;

cast.cast just doesn't make sense at all.

Upvotes: 1

user2711965
user2711965

Reputation: 1825

You can pass the List<Cast> to your event, Have a class level index on list and increment that index each time in the event something like:

actorTimer.Elapsed += new ElapsedEventHandler((sender, e) => RunActorEvent(sender, e, liCast));

Then in method:

int index = 0; //class level index
public static void RunActorEvent(object sender, ElapsedEventArgs e, List<Cast> list)
{
    int personId = list.ElementAt(index++); //or list[index++]
    _actors.Add(_api.GetPersonInfo(personId));
}

Upvotes: 1

Related Questions