It seems that the problem is not what I think.
The problem is that I have two lambdas binding fields in the parent: the compiler generates a class with two methods and a link to the parent class ( this ).
I think this will be a problem because the reference to this could potentially remain in the TaskCompletionSource object, preventing it from being a GCed. At least this is what I found on this issue.
The generated class will look something like this (obviously, the names will be different and unpronounceable):
class GeneratedClass { Request _this; TaskCompletionSource tcs; public lambda1 (Object e, ElapsedEventArgs a) { tcs.SetException(new TimeoutException("Timeout at " + a.SignalTime)); } public lambda2 () { tcs.SetResult(_this._response); } }
The reason the compiler does this is probably efficiency, I suppose since TaskCompletionSource used as lambdas; but now, while a reference to one of these lambdas still refers to a reference to a Request object, it is also supported.
I am still not closer to figuring out how to avoid this problem.
EDIT: I obviously did not think about it when I wrote. I solved the problem by changing the method as follows:
public Task<Response> TaskResponse { get { var tcs = new TaskCompletionSource<Response>(); Timeout.Elapsed += (e, a) => tcs.SetException(new TimeoutException("Timeout at " + a.SignalTime)); if (_response != null) tcs.SetResult(_response); else ResponseHandler += tcs.SetResult;
Aaron Maslen Oct 18 2018-12-18T00: 00Z
source share