10

Apparently Close and Dispose are effectively the same. I want to be able to Close and Open my ServiceHost instance without having to reinstantiate it everytime. Any ideas? Thanks.

Sam
  • 2,663
  • 10
  • 41
  • 60
  • or to rephrase the question - how can I "disable" myServiceHost without calling Close? – Sam Feb 11 '11 at 00:32

1 Answers1

12

ServiceHost.Close is effectively identical to Dispose(). This is true, in general, with all types that have a Close() method - Dispose() is implemented in terms of Close().

FYI - ServiceHostBase implements Dispose() explicitly via:

void IDisposable.Dispose()
{
    base.Close();
}

This, effectively, means that when you close the ServiceHost, you'll always Dispose() of it. There is no supported way to "reopen" it without recreating it.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • @Reed Copsey, thanks for your response. Let me rephrase the question, can I "disable" the serviceHost object without calling Close? – Sam Feb 11 '11 at 00:16
  • @Sam: Nope. Close it, and recreate it when you want to "enable" it again. – Reed Copsey Feb 11 '11 at 00:21
  • Why do you want to "disable" the serviceHost? The service should always be available to its callers. – Richard Schneider Feb 11 '11 at 00:21
  • @Richard, I'm testing my WCF service being hosted in a WinForms app.. and more specifically, I just want to be able to minimise unnecessary memory re-allocation. I'm coming from a Delphi background so I want more control of my objects ;-) – Sam Feb 11 '11 at 00:26
  • 1
    @Sam: Get out of that habit. You'll find that thinking that way actually, when you're all said and done, hurts you more than helps. Allocations in C# are cheap - unlike native code - it's often faster to let the object get collected and reallocate than it is to try to prevent it, especially if its not long lived... – Reed Copsey Feb 11 '11 at 00:30
  • @Reed, deallocating memory and re-allocating it again can be faster than checking a boolean flag and going down a tree branch that's got half the instructions of the usual dispose/recreate routine? are you serious? Maybe if the code was being interprited line by line everytime it was executed! Don't tell me that's what's happening. – Sam Feb 11 '11 at 00:38
  • 1
    @Sam: Depends on what you're doing. If there was a simple "IsEnabled" property, then of course not. However, you'd be surprised - I've found that doing things I used to think of as required (ie: lifting allocations out of loops) will often slow down a C# program instead of improving them... – Reed Copsey Feb 11 '11 at 00:42