开发者

Downsides to starting a thread in the same context using an anonymous delegate

So the following code is possible in C# to start a new thread in a method:

int myInt;
new Thread(delegate() {
    // yeah, I'm in a separate thread! And I can access myInt as well, awesome
}).Start();

and all your local variables in that scope are also available in that thread. I've used this in times where I need to perform small calculations "on the side" instead of creating small methods and starting them as threads instead, so I find it quite useful, even if it's not that pretty always.

Recently I also got in the situation where I needed to break of a long going thread that needed 5 variables from the calling method, and it got me wondering whether or not this was "good coding" considering both scopes need references to the local variables.

I am therefore wondering if it is better to create a new class (something in the lines of SpecificContext) 开发者_运维百科and pass that as an object to a Thread using the ParameterizedThreadStart delegate or if this design is actually considered as "best practice" since we kind of get type checking of the variables? Also, are there any downsides to using one approach over the other, in both design and/or performance?


Since myInt was used by the delegate, the compiler created a hidden class to convert myInt from a normal stack variable to a reference of an heap variable. In effect, it created a start parameter object for you. Since the compiler is doing all right things for you, I would use the most readable code. In this case, I suspect it would be using myInt 'directly'.

Note that you have no better control over this automaticaly generated object over one you generate yourself. You still have to worry about synchronization, if both threads are accessing these start objects.


When you have a anonymous method, C# compiler generates a class for you. This class contains all local variables, referenced inside a delegate and it is not synchronized.

It is definetely better to create a class and pass variables because you'll have control over the synchonization.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜