A rather simple question (I think), but I don't seem to see an answer already. I know that some values are passed via value (like int and long), and others are passed by reference (like Strings) when you pass them to functions.
In my program, I have it using background worker so that the GUI doesn't lock up when we are doing a long process in the background. I need to pass data back to the UI thread from another file, so I have been using events for that. Now I need to send a list of arrays of Strings back to the GUI thread to handle there, and I am worried how it will be handled. Basically, in the worker thread, I have a loop that will fill up the list, send it back to the GUI via an event handler, and then clear it so it can fill it up on the next pass through the loop and start again.
I am worried that when I do this, if the list is passed by reference, then on the UI thread, I would think that it would be cleared mid-read since the worker thread will still be clearing it in the background. Passing by would be far preferable in this case, and I can find ways to force it(copy to some holder array or add a mutex or something of the sort), but I thought it would be good to know if event arguments are passed via reference or value in general, or is it just the same as methods, and it will pass them as arguments are normally passed?
I know that some values are passed via value (like int and long), and others are passed by reference (like Strings) when you pass them to functions.
Nope. By default everything is passed by value - but when you're using reference types, the "everything" is a reference. That reference is passed by value. That's not the same as pass by reference. See my article on parameter passing for more details.
Event arguments are exactly the same - any references are passed by value, assuming the corresponding delegate doesn't use out
or ref
parameters.
EDIT: So to address your concern: yes, if your event argument is mutable and you're going to act on a different thread, you should create a copy first... or alternatively, pass the existing reference and then create a new (empty) list in your worker thread.