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

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

c# - What gotchas exist with Tasks and Garbage Collection?

When does a developer need to be concerned with the effects of garbage collection when using APIs and classes derived from the Task Parallel Library?

Can .NET Task instances go out of scope during run?, would seem to give a sense of security that you do not have to worry about keeping tasks in scope. However the question seems limited to Tasks running on the ThreadPool where they are then rooted by the ThreadPool. However, if I understand this MSDN blog post correctly, the advice from that SO question is not be generally applicable because Tasks from TaskCompletionSource are not similarly rooted.

Are direct use of TaskCompletionSource the only time of concern?
However, when consuming an API you do not know where the Task came from. Do you then need to worry about storing references to continuations in case the provided Task came from a TaskCompletionSource or some other non-rooted source?

This seems to get inconvenient and complex quickly from needing to consider whether the Task is rooted or not (are Async I/O Tasks rooted?). I am struggling to find much for information on topic but it a popular enough library I feel I should not need to be reading decompiled source code to determine if I need to worry about race-conditions with the garbage collector, so I figure I must be missing or misunderstanding something.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

When you have uncompleted TaskCompletionSource, then there are always two options:

  1. Something might complete that TCS in the future. That means that that something holds a reference to the TCS, which means it can't get GCed.

    Normal rules still apply to that something, so you might need to worry about keeping that rooted.

  2. Nothing will ever complete that TCS. That means the TCS and its Task will likely get GCed soon, but there is no risk of work not being done (because there is no work).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...