VBScript error handling in C#
I want to access WMI using the AutomationFactory
in a Silverlight OOB application.
dynamic locator = AutomationFactory.CreateObject("WbemScripting.SWbemLocator");
dynamic wmi = locator.ConnectServer(".", "\\root\\cimv2");
I now want to add error handling to this.
MSDN states that the return value is a reference to the connected object if the call is successful and that in case of an error I should check the Err
object. However, there are two questions I have with this:
- What is the return value if the call is not successful? null? Some arbitrary pointer that I cannot use?
- How can I access the
Err
object in Silverlight? - How can I detect if the call was 开发者_StackOverflowsuccessful? May there be any exceptions which I have to catch?
- I've seen some examples using the
using
statement, and some without. Do I have to dispose the dynamic objects manually after I've used them?
- What is the return value if the call is not successful? null? Some arbitrary pointer that I cannot use?
No value is return and the LHS of an assignment is unmodified when a call into a COM component fails. Instead the COMException
is thrown.
- How can I access the
Err
object in Silverlight?
This is no "Err" object, that is a VB(Script) construct, it doesn't exist in C#. However the infor you are after will be available as the properties of the COMException
thrown when a call fails.
- How can I detect if the call was successful? May there be any exceptions which I have to catch?
Yup, see above.
- I've seen some examples using the
using
statement, and some without. Do I have to dispose the dynamic objects manually after I've used them?
Attempts to manage COM object lifetimes using Dispose have varied results. Personally I'd make sure that anything that has something like a "Close" method has that "Close" method call and leave it at that.
If you really want to make user COM objects are released then at an appropriate point (and not too frequently) call GC.Collect
.
精彩评论