C# Async call garbage collection
I am working on a Silverlight/WCF application and of course have numerous async calls throughout the Silverlight program. I was wondering on how is the best way to handle the creation of the client classes and subscribing. Specifically, if I subscribe to an event in a开发者_C百科 method, after it returns does it fall out of scope?
internal MyClass
{
public void OnMyButtonClicked()
{
var wcfClient = new WcfClient();
wcfClient.SomeMethodFinished += OnMethodCompleted;
wcfClient.SomeMethodAsync();
}
private void OnMethodCompleted(object sender, EventArgs args)
{
//Do something with the result
//After this method does the subscription to the event
//fall out of scope for garbage collection?
}
}
Will I run into problems if I call the function again and create another subscription?
Thanks in advance to anyone who responds.
You shouldn't let WCF client proxies simply fall out of scope like this. Your code will work but it will also leak resources. WCF clients all implement IDisposable
, but this is one case where you can't just use using
or Dispose
; the Service Proxy Helper can be used for synchronous operations but the cleanup code in there demonstrates how to safely dispose of the client in any context.
When making async operations like this, something needs to be managing the lifetime of that client in a similar fashion. Normally whatever class "owns" the WCF client should implement IDisposable
itself, keep a reference to that client in a private field somewhere, and invoke Close
/Abort
on the client in its disposal method.
Generally, whichever class actually implements the async callback method is going to be the owner, and so that class should be managing the lifetime; therefore, if you really need an "on-demand" client, it may also make sense to perform the cleanup after the callback is finished.
WCF clients are not cheap to create, either, so you should actually try to keep them around as long as possible and not create them ad-hoc like this; think of them as application-wide dependencies.
If you just keep the client instance around, then you don't need to keep subscribing to its events, either; the question effectively goes away.
You won't run into problems. It will generate a new WcfClient
instance, and both will call your OnMethodCompleted
callback on completion.
精彩评论