C# - Recovering From Exception from Interop - c#

I've purchased a third party library that I am using from my application. My application references a small interop dll which in turn calls into another dll (non CLI) to do its thing. Since this library communicates with hardware, I'd image that this dll talks with various device drivers.
A typical method signature from the interop dll looks like this:
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType=MethodCodeType.Runtime), DispId(0xc9)]
public virtual extern void Send([MarshalAs(UnmanagedType.Struct)] ref object pVal);
I have all calls to this library wrapped in one large try catch(Exception). If anything goes wrong with sending I need to mark it as failed and move on. Unfortunately, my application will just randomly close with no exception. Is there anything I can do about that? These calls are already being made on a separate thread By using Task.Factory.StartNew(), but the whole application just quits. In addition to a local try catch, there is another one wrapped around the call to StartNew (I have a call to .Wait() just for debugging purposes). That catch doesn't fire either.
Right now I'm thinking the only solution is to create a separate program that simply waits for the other to close and then re-open it. Which sounds horrid...

Take a look at this blog you might be able to get a crash report and at leas see what call is failing and report it to your 3rd party developer.

Related

How to approach removing needless instantiation when calling native method from WebAPI

I have a dotnet core WebAPI web server that needs to execute a native method written in Win32 C++. The problem is, each time this method is called it needs to instantiate a bunch of things before it can do what it needs to do, this adds delays to the request. (It's currently using DLLImport to access the C++ method in the compiled DLL).
What I would like to do is have some sort of long running process start when the server starts, which will handle the initialization once, then have my WebAPI service call a method inside this process that executes the code that I actually need to run immediately, without the need to initialize its dependencies each time. Since this is a web server, the process will need to be able to handle multiple requests at once.
What is the recommended approach for this? I have full access to the C++ code and the WebAPI server code so I'm free to do whatever needs to be done to accomplish this.
You may set-up some IPC infrastructure between the two.
One way to do it would be to make your DLL COM compatible. I.e having the DLL be a COM server to some COM class. The server process would then 'CreateInstance' a class, which will automatically launch your native process. A call would then just be a normal function call, COM will handle the RPC.
Another simpler way will be using a named memory-mapped file. Both processes will open a handle to this, there you can store a queue or some data structure. The server process will push while the native process will pop. You can use windows events to synchronize this. You can write this yourself or use something like boost::interprocess for the C++ part. I assume there may be other IPC libraries you may find for this.
You can also use a Pipe, I know C# has some easy ways to handle windows pipes. Pipes do not need synchronization but to efficiently handle a number of such requests you may need a number of threads on the native process to read from the pipe.
Personally i'd go with using COM if that is possible. As it will hide for you the low-level IPC stuff that may be a pit-fall. It is a bit longer to set-up though.

Prevent native C++ DLL crashing C# App

We have a c# WPF app and we use a 3rd party SDK with a native C++ DLL, we call the methods with DllImport attributes.
Unfortunately code is not that great and that C++ DLL crashes our C# app.
Is there an elegant and efficient way to isolate the calls to the C++ DLL so their exceptions don't crash our app? We are getting a stream of images and data so it needs to be fast.
We use WCF to offload some operations in a windows service, so we have an infrastructure to do this, but I don't think it will be fast enough to transfer data and image buffers to/from it.
Would a different AppDomain be a good choice? Any examples how to do this?
thanks
Its probably the right behaviour to terminate the app in this situation. If you have control over the DLL I would consider handling its exceptions differently
From memory, i believe (in early versions of .Net) you could just catch via ExternalException class:
Note : .NET v4 and above it disables the delivery of certain exceptions by default
To reenable this i 'believe' you can just edit your manifest or use an attribute, take a look at
legacyCorruptedStateExceptionsPolicy Element
HandleProcessCorruptedStateExceptionsAttribute Class
a similar crash occured to me not long ago.I think first you should resove the native dll error . There is no way that you can use to catch an exception from a native code.
The only way to make sure the C++ DLL does not crash your C# process is to move it to another process which you can restart if it crashes.
You can wrap the C++ DLL in a separate application / service and communicate with your C# application via named pipes to transfer the image data. You will also need some kind of heart beat to detect if the wrapper crashed and restart it as needed.
We implemented this solution for a microscope which came with an ActiveX component that kept crashing our application. This approach worked well and was fast enough.
AppDomains don't provide isolation for native assemblies as they use unmanaged memory, due to this I'm not sure if an access violation in a secondary app domain will bring down your whole process.
I'm guessing that your problem is due to state corruption. So before trying to outboard the service you can try catching those exceptions.
How to handle AccessViolationException
So long as the library itself can recover, you might be OK. Worth giving a go.

How to deal with exceptions on separate threads in an external dll?

I'm loading in a dll that spawns a few threads within itself. Every now and then the program crashes with an unhandled exception. I can't wrap all my library calls in try/catch statements because the exceptions are being thrown on separate threads, and I don't have access to the library's source to debug/fix the bad error handling. I'd like the program to keep doing other things when these exceptions happen, is there a graceful way to handle these exceptions? Or is the only thing I can do to do a global catch all exceptions method?
If you load the DLL into a separate appdomain, you should be able to isolate exceptions generated with a AppDomain.UnhandledException, but, be aware that this is not fool proof and there are certain situations where it will still take your process out too and there is nothing you can do about it (stack overflow, out of memory etc).
The best you can do in that case is load them in a separate process completely with some kind of dll communication harness and using some form of remoting to talk to that process.
I would recommend to implement a separate process (EXE) which your application launches and which in turn loads the DLL.
This allows you to kill/restart the process whenever need be...
I see several options on how to communicate - for example:
you could use COM (if you implement it as an out-of-process COM server)
you could use shared memory (very high performance, see this for a walkthrough and this for a .NET 2 wrapper)
IF the method must be compatible with several Windows versions THEN I would refrain from using anything "networky" for the IPC (since some come with a desktop firewall).

Calling a c# .dll from native visual c++ code

the system I'm working with consists of:
A front-end application written in most likely VB or else VC++ (don't know, don't and can't have the sources for it)
An unmanaged VC++ .dll
A C# .dll
The application calls the first dll, the first dll calls different methods from the second one.
In order to make the first dll able to see and call the C# code I followed this guide:
http://support.microsoft.com/kb/828736
The only difference is that i am not compiling with /clr:OldSyntax, if I do then changing the other dependant compiling options makes the first dll load incorrectly from the application.
Everything compiles smoothly; the whole setup even worked fine initially, however after completely developing my code across the two dlls I now get an error in the application. The error is:
Run-time error '-2147417848 (80010108)':
Automation Error
The object invoked has disconnected from its clients.
And occurs when the following line is executed in the first dll:
MyManagedInterfacePtr ptrName(__uuidof(MyManagedClass));
I tried reproducing a fully working setup but without success.
Any ideas on how the heck I managed to do it in the first place?
Or alternatively on other approaches for making the two dlls work together?
Thanks in advance!
It is a low-level COM error, associated with RPC. That gets normally used in out-of-process servers, but that doesn't sound like your setup. It would also be used if you make calls on a COM interface from another thread. One possible cause is that the thread that created the COM object was allowed to exit, calling CoUninitialize and tearing down the COM object. A subsequent call made from another thread would generate this error. Getting reference counting wrong (calling Release too often) could cause this too.
Tackle this by carefully tracing which threads create a COM object and how long they survive.

How to write a lib in C#, the lib can be run without any invoked?

i want to write a C# lib, or a reference service,
so that if a application reference my lib, and when the application runs,
the function in my function can be run without any invoked?
for example, i got a lib, keep reading the memory usage of the platform,
when the memory was up to 80%, i pop up a message to the user, it is time to close the application.
so..when i create a another application, and want my new application has the mem check feature, i just need to reference it then after my new application run, the mem check will be fired together..
so..how can i do these?
Create a static constructor for your class - this constructor will be run once, and only once, the first time the host application references anything related to your class.
You could create a thread to run some background checking process, hook into an event of the Application object, or whatever you need.
Note however, that you'll need to do more than just add a project reference to your assembly - an assembly is only loaded into an App Domain when something in that assembly is referenced by existing code.
The term you're looking for is "Win32 application hook." There's a decent introduction to managed hook injection here: http://msdn.microsoft.com/en-us/magazine/cc188966.aspx
I'm not sure you can monitor system memory consumption with an application hook, though. And unfortunately, you cannot write a global hook in managed code because global hooks require a well-defined entry point (a DLL export). This is really something best suited for C++.
It is possible to create traditional DLL exports in an assembly (via ILASM or the now defunct Delphi.NET) but not really recommended. (search for reverse p/invoke)
Another approach is to create a C++/CLI intermediate dll to call your managed code. But to be perfectly honest, I reckon you are simply better off just creating a native DLL with C++ or Delphi.
Edit:
Ok, firstly a disclaimer, I work for Quest Software (the company that makes this tool that I am about to plug). That said...
OS Monitoring is actually not as straight forward as you might think, things like memory consumption, process monitoring etc is...well, pernickety. You may find that somthing like Spotlight on Windows (Freeware for first 10 licences) would suit your purpose ?

Categories

Resources