Why These two c# scripts give different results? [duplicate] - c#

This question already has answers here:
Regarding local variable passing in Thread
(2 answers)
Closed 2 years ago.
I'm working on a big list of buttons and trying to AddListener() for every Button on this list using a quick way
the first way is
btn[0] = CHbutt[0].GetComponent<Button>(); btn[0].onClick.AddListener(delegate { CH(0); });
btn[1] = CHbutt[1].GetComponent<Button>(); btn[1].onClick.AddListener(delegate { CH(1); });
btn[2] = CHbutt[2].GetComponent<Button>(); btn[2].onClick.AddListener(delegate { CH(2); });
btn[3] = CHbutt[3].GetComponent<Button>(); btn[3].onClick.AddListener(delegate { CH(3); });
and it works very well, and AddListener() to all Buttons in btn[];
but a lot of lines...
the second way
for (int i = 0; i < CHmatt.Count; i++)
{
btn[i] = CHbutt[i].GetComponent<Button>(); btn[i].onClick.AddListener(delegate { CH(i); });
}
but this one is not working, this one AddListener() to only the last button btn[0]
I'm very curious about the difference between these two scripts.

It's a capturing issue. Change the code as follows, to avoid capturing i:
for (int i = 0; i < CHmatt.Count; i++)
{
var ii = i;
btn[i] = CHbutt[i].GetComponent<Button>();
btn[i].onClick.AddListener(delegate { CH(ii); });
}
What is being passed into AddListener function is a delegate method; however, since you're passing in a loop iteration variable i, the context is captured, and i is actually referenced. As your loop advances, the value of i changes for all captures, therefore making this approach "not work".
By introducing a local copy of i (the name is not material here, I called it ii), which goes out of scope on each loop iteration, the capture of i is avoided, and the actual value of ii is passed to the delegate method (technically, captured, but it's a copy of i for each loop iteration, and therefore does not change as i changes.)

Related

C# Referencing the value of a variable [duplicate]

This question already has an answer here:
Is it possible to instantiate objects with variable names, or access variable names at runtime?
(1 answer)
Closed 1 year ago.
I'm having difficulty understanding how I can reference the return value of a variable to create another in C#.
string name = Console.ReadLine();
List<Thing> name = new List<Thing>();
For example, user inputs "Cats" and thus a new list Cats is created.
Or in this scenario:
for (int i = 0; i < 5; i++)
{
List<Thing> (animal + i) = new List<Thing>();
}
Where the lists created becomes animal0, animal1, animal2... etc.
Thank you
You cannot do that in C# at least not naturally.
Variable are determined at the compile time.
Value you are talking about (Cats, animal0, ...) are determined at the runtime, when the code is really running, which occurs after the compilation. So those values cannot become variable names.
You cannot create variables dynamically at runtime, so every variable you would like to use needs to be declared on compile time. Nevertheless, a List<Thing> can hold multiple instances of a Thing at the same time, representing - in your sense - multiple variables.
For example:
var things = new List<Thing>();
for (int i = 0; i < 5; i++) {
things.Add(new Cat()); // if Cat derives from Thing
}
// access the list items by index
Console.WriteLine(thing[0]);
Console.WriteLine(thing[1]);
...

C# Asynchronous task with multiple parameters [duplicate]

This question already has answers here:
Captured variable in a loop in C#
(10 answers)
Closed 2 years ago.
I need to run tasks in parallel and transfer about 3-5 parameters to them, but now I transfer 2 parameters to the task, and as a result, I always see the value 100 in the console.
Tell me what am I doing wrong? and how to correctly pass parameters to the task?
class Program
{
static void Main(string[] args)
{
/// Init
string file_name = "unknown.dat";
Action<string, int> action = (msg, count) => Load(msg, count);
/// For
for (int i = 0; i < 100; i++)
{
Task.Factory.StartNew(() => action(file_name, i));
}
/// End
Console.Read();
}
public static void Load(string aFileName, int aCount)
{
Console.WriteLine("Index: {0} ", aCount);
}
}
This is a "captured variable" problem; try instead:
for (int i = 0; i < 100; i++)
{
var copy = i;
Task.Factory.StartNew(() => action(file_name, copy));
}
The fundamental problem here is that your action is capturing the variable i, not the value of i at a particular time. So what happens is: your loop finishes really quickly (before the thread-pool has even got its shoes on), and i ends up at 100. At some indeterminate time the thread-pool starts processing your work items, and the i is sat at 100 for all of them. Note: it is technically possible to get earlier numbers, but that is ultimately a massive race condition.
The fix here moves the declaration of the captured variable to inside the loop; the declaration of a variable defines the scope for the purposes of captured variables, so now each copy is independent of the others.

Thread safety with method parameters reference vs value [duplicate]

This question already has answers here:
Captured variable in a loop in C#
(10 answers)
Closed 3 years ago.
My understanding about thread safe method parameters is: Parameters passed into a method by value are delivered as copies of the data that was given in the arguments to the method call, so they are unique to that method call and cannot be changed by any other task. Reference parameters, conversely, are susceptible to change by code running in other tasks.
With that said, It is not perfectly clear to me why the following code (without making a local copy of the loop counter) returns the same number in every thread.
static void ExampleFunc(int i) =>
Console.WriteLine("task " + i);
for (int i = 0; i < 10; i++)
{
int taskN = i; //local copy instead of i
Task.Run(() => Func(i));
}
The actual output is: task 10 ten times
I get the correct output (task 1 to 10) by passing taskN instead of i.
I expected the same result since I'm passing a type value parameter.
Parameters passed into a method by value are delivered as copies of the data that was given in the arguments to the method call,
The question is really: when does that copy happen?
It isn't when you Task.Run(...);; rather - it is when the actual lambda gets invoked by the thread-pool, i.e. when the Func(i) gets executed. The problem here is that in most cases, the thread-pool will be slower than your loop on the active thread, so those will all happen after the loop has finished, and they will all access the same captured value of i. Ultimately, what you have is:
class CaptureContext {
public int i;
public void Anonymous() { Func(i); }
}
...
var ctx = new CaptureContext();
for (ctx.i = 0; ctx.i < 10; ctx.i++)
{
int taskN = ctx.i; // not used, so will probably be removed
Task.Run(ctx.Anonymous);
}
i.e. there is only one single i, so if all the anonymous methods get invoked after the loop, the value for all of them will be: 10.
Changing the code to:
int taskN = i; //local copy instead of i
Task.Run(() => Func(taskN));
gives you very different semantics:
class CaptureContext {
public int taskN;
public void Anonymous() { Func(taskN);}
}
...
for (int i = 0 ; i < 10 ; i++)
{
var ctx = new CaptureContext();
ctx.taskN = i;
Task.Run(ctx.Anonymous);
}
Note that we now have 10 capture context instances each with their own taskN value that will be unique per context.

C# Passing array of string element into a Task.Run

Trying to pass an element of an array of strings into a function which is being called in a Task.Run. Anyone know what is the error here?
The code here doesn't work, it behaves as if ProcessElem never gets called.
string[] arr = message.Split(new string[] {"\n"}, StringSplitOptions.None);
for (int i = 0; i < arr.Length; i++) {
if(arr[i] != "") {
var t = Task.Run(() => this.ProcessElem(arr[i]));
}
}
However the code below works
string[] arr = message.Split(new string[] {"\n"}, StringSplitOptions.None);
for (int i = 0; i < arr.Length; i++) {
if(arr[i] != "") {
var tmp = arr[i];
var t = Task.Run(() => this.ProcessElem(tmp));
}
}
I'm very new to how C# does things, but it seems like both patterns are unsafe because the function that calls Task.Run() might return before the ProcessElem function executes, and if the strings are pass by reference then they will be destroyed before ProcessElem is called.
If this is the case, what would be the best way to pass the string into ProcessElem?
Also, why doesn't the first version actually "call" ProcessElem? I have a print statement at the top of ProcessElem and it only gets printed # the second version.
Welcome to captured variables.
Task.Run(() => this.ProcessElem(arr[i]))
This essentially means:
Take my lambda action: () => this.ProcessElem(arr[i])
Run it after you've found/created a thread to do so. i.e. some time later.
However, there's only one variable involved, i, and that's defined outside your lambda action's scope, it's not being copied, the same variable is just being captured and referenced.
By the time that thread gets around to executing, the value of i has most likely changed. Usually, the loop finishes before the threads perform their work.
That means that by that time, i equals arr.Length and all threads try to access arr[arr.length] which obviously results in an IndexOutOfRangeException.
When you do var tmp = arr[i];, you are creating a fresh variable per loop iteration, copying the loop variable and capturing that copy in your lambda, which is why it works.
The source of your problem is how the actual "coroutines" work in C#
i is not passed as the current value but rather as ref i which means that your Action always will receive the current i value when it gets executed.
Chances are, you run this code and the Tasks are not executed in parallel. That means, the specific task executed gets the current value of i which, in most simple cases, will be as provided as exit condition: arr.Length + 1
to proof:
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] != "")
{
var j = i;
var t = Task.Run(() => ProcessElem(arr[j]));
tasklist.Add(t);
}
}
will work perfectly fine (unless you have some problems in your ProcessElem method :P)
in regards of string-destruction, unless you got some object that implements IDisposable, you should be fine with passing it into some lambda.
It will exist, until the actual lambda got deleted (as it will retain some reference to the object eg. in this case arr)
Your problem is an age old issue, its how lamdas work, and its very well documented.
However, assuming you are just creating and awaiting a bunch of tasks, then save your self code, hassle, and task creation and just use TPL Parallel.For or AsParallel
Parallel.For(0, arr.Length, (i) => ProcessElem(arr[i]));
Or
arr.AsParallel().ForAll(ProcessElem);
Or if you really don't want empty strings
arr.Where(x => !string.IsNullOrEmpty(x))
.AsParallel()
.ForAll(ProcessElem);

Why does this output 333 not 0112 at Array.ForEach? [duplicate]

This question already has answers here:
Is there a reason for C#'s reuse of the variable in a foreach?
(4 answers)
Closed 8 years ago.
Why the below code ouput 333 not 012?
I think the code is so simple and I check and check and double check, triple check, can not get answer yet. Any one can help me?
Action[] tmp = new Action[3];
for (int i = 0; i < tmp.Length; i++)
{
tmp[i] = () => Console.WriteLine(i);
}
Array.ForEach(tmp, m => m());
Console.Read();
You should change your code to:
Action[] tmp = new Action[3];
for (int i = 0; i < tmp.Length; i++)
{
int j = i;
tmp[i] = () => Console.WriteLine(j);
}
Array.ForEach(tmp, m => m());
Console.Read();
The reason is closure is nest
More detailed information please see those links:
Is there a reason for C#'s reuse of the variable in a foreach?
http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/
This occurs because there is only one i variable in the original code as for does not introduce a new variable "each loop" and the same variable is closed over in all the closures! As such, the same (i) variable is assigned the last value (3) before any of the functions are executed after the loop.
Compare with the following code which ensures a new variable to bind in each closure (this is one rare case where I use underscores for a local variable to show "something funny" is happening):
for (int _i = 0; _i < tmp.Length; _i++)
{
int i = _i; // NEW/fresh variable, i, introduced each loop
tmp[i] = () => Console.WriteLine(i);
}
This behavior (and complaints against) is discussed in detail in Is there a reason for C#'s reuse of the variable in a foreach? - for and foreach have this same "issue" in C#4 and before, which is "fixed" for foreach in C#5.
I think it is fair to say that all regret that decision. This is one of the worst "gotchas" in C#, and we are going to take the breaking change to fix it. In C# 5 the foreach loop variable will be logically inside the body of the loop, and therefore closures will get a fresh copy every time. - Eric Lippert

Categories