So I want to queue some actions to be invoked.
A little background: trying to send requests using Webclient but apparantly it doesn’t allow very long URLS (upward of 2000 characters) and found the upper bound for that value in my system is around 40 items (43 to be exact). So I need to split the Webclient requests into sets of 40~ and have decided to do so using a Queue.
Here is the code:
public void some_method()
int num = 40; // readonly variable declared at top but put here for clarity
String hash = "";
Queue<Action> temp_actions = new Queue<Action>();
foreach (ItemViewModel item in collection)
{
num--;
hash += "&hash=" + item.Hash; // Add &hash + hash to hash
if (num == 0)
{
// Change status for these 40 items
temp_actions.Enqueue(() => auth.change_status_multiple(status, hash));
// Reset variables
num = 40;
hash = "";
}
}
// Enqueue the last action for the rest of the items
// Since "num == 0" doesn't cater for leftovers
// ie. 50 items and 40 in first set, 10 left (which will be enqueued here)
temp_actions.Enqueue(() => auth.change_status_multiple(status, hash));
// Start the change status process
temp_actions.Dequeue().Invoke();
actions = temp_actions;
}
public Queue<Action> actions { get; set; }
// Event handler for when change_status_multiple fires its event for finish
private void authentication_MultipleStatusChanged(object sender, EventArgs e)
{
if (actions.Count > 0) // Check if there are actions to dequeue
actions.Dequeue().Invoke();
}
But when it comes to runtime, hash will be “”.
For example, I have 50 items, 40 will be in the first action enqueued, then 10 in the second, however the hash String for the first set is “”. Why is that? I would’ve thought that upon enqueuing the action into the Queue it would keep whatever values for the variables I supplied at that time.
I debugged my code and upon enqueuing the first set, hash is correct, but when it goes to reset the variables num and hash, hash is changed for the first set (inside the queue) to “”.
Is there anyway around this?
Thanks.
You’re a victim of deferred execution… You’re capturing scope of
hashin the delegate on the following line:then immediately clearing
hashto “”.When the delegate runs,
hashhas already been cleared.To fix, take a local copy of
hash