Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

When using System.Threading.Tasks.Dataflow, if I link block a to block b, will the link keep b alive? Or do I need to keep a reference to b around to prevent it from being collected?

internal class SomeDataflowUser
{
    public SomeDataflowUser()
    { 
        _a = new SomeBlock();
        var b = new SomeOtherBlock();
        _a.LinkTo(b);
    }

    public void ReactToIncomingMessage( Something data )
    {    
        // might b be collected here?
        _a.Post( data );
    }

    private ISourceBlock<Something> _a;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
125 views
Welcome To Ask or Share your Answers For Others

1 Answer

You're confusing variables with variable contents. They can have completely different lifetimes.

Local variable b is no longer a root of the GC once control leaves the block. The object that was referenced by the reference stored in b is a managed object, and the GC will keep it alive at least as long as it's reachable from a root.

Now, note that the GC is allowed to treat local variables as dead before control leaves the block. If you have:

var a = whatever;
a.Foo(); 
var b = whatever;
// The object referred to by `a` could be collected here. 
b.Foo();
return;

Because for example maybe the jitter decides that b can use the same local store as a since their usages do not overlap. There is no requirement that the object referred to by a stays alive as long as a is in scope.

This can cause issues if the object has a destructor with a side effect that you need to delay until the end of the block; this particularly happens when you have unmanaged code calls in the destructor. In that case use a keep-alive to keep it alive.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...