Preventing code being loaded to another AppDomain - c#

We have a plugin for excel that is normally working fine, and we don't have anything set up for using AppDomains.
However, some other plugin seems to force our code to load the second time, and we end up having our code running on two different AppDomains (when we want to execute an action, we will put it in a queue on AppDomain 1, and then, the Excels OnTime function runs dequeue method on AppDomain 2, where the queue is empty).
So, my question is this: is there a simple way to get around this problem, maybe prevent our program from being loaded twice or by other AppDomains? Does anyone have any other idea on how to approach this issue?
Update:
What we managed to do, was to load our whole program into other plugin's AppDomain when we are called, and now we have strangest problem at the same places (places that used to be "gateways to other domains", like the mentioned action queue function):
The SynchronizationContext.Current seems to reset to null whenever there is such case, for example for every call of the click handler on ribbon, the SynchronizationContext.Current is set to null.
I even tried debugging the .Net code, and it happens that framework remembers an old synchronization context, and when getting everything back to how things were, old synchronization context is null.
Can anyone give any help on this issue, I'm really starting to lose it?

I think this could be a solution for your problem:
http://ingebrigtsen.info/2007/05/18/cross-appdomain-singleton/
and an update to the post above:
http://web.archive.org/web/20120427003305/http://www.dolittle.com/blogs/einar/archive/2007/05/30/crossappdomainsingleton-update.aspx

Related

Window "capture" application, upon unexpected termination, allows captured windows to disappear, how can I prevent/fix this issue?

I have an application (C# + WPF) that attempts to wrest control of the graphical interface of any process passed to it as an input and resize/reposition for my own purposes.
It does its job rather well, I think. Upon expected termination (the base class inherits from IDisposable) the "captured" process is released - its parent is set to the original, its windowstyle is reset, etc. etc.
In fact, on testing, I can capture, release, recapture, and so on, the same process as many times as I want with no issues.
However, upon unexpected termination (say another process forcefully kills it), the process never regains its graphical interface! I can tell its still running but I can never set that process back to its original state.
It almost seems like the process doesn't respond to window-based Win32 API calls that set specific window features anymore (for example, I can get information with GetParent, GetWindowThreadProcessId, etc but calling ShowWindow or related results in nothing).
Any suggestions on why this is happening? I'm guessing that since I set the parent of the process to my WPF application (which then unexpectedly closes) it causes some issue in trying to recover the initial interface?
This is why it's happening (or, at least, an indication of why I had so much difficulty finding the issue out on my own); can I recover from it? And, if so, how?
Edit -
IInspectable makes a good point in the comments, question adjusted to make better sense for this particular application.
It seems I've gotten my answer; so, for the sake of completeness I'll post what I've gotten here in case anyone else has a similar issue.
According to the information provided by IInspectable in here and here (with more context in the comments), it seems that what I'm trying to do here (assign a new parent cross-process) is essentially unsupported behavior.
My Solution:
Recovering (at least at the point that I'm talking about - i.e. unexpected crashes or exits) probably isn't feasible, as we've already gone off the end in undetermined/unknown behavior. So I've decided to go for the preventative route.
Our current project already makes use of the Nancy framework to communicate across servers/processes so I'm going to "refine" our shutdown procedure a bit for my portion of the program to allow it to exit more gracefully.
In the case of a truely unexpected termination, I'm still at a loss. I could just restart the processes (actually services with a console output, in our case, but w/e) but my application is just a GUI/Interface and isn't very important when compared to the function these processes serve. I may make some sort of semaphore file that indicates whether a successful shutdown occurs and branch my code off so that it indicates that the processes are no longer visible until the next time they're restarted.

How to gracefully handle calling a method that may never return

In my C# MVC4 ASP.NET code (in a method on a controller) I call a function that I know has the possibility that it may never return. It is a call to a Microsoft object that does not raise and error, does not time out, just hangs (and hangs and hangs).
I think I have found the cause of the specific incidents of why this has happened, but the general problem worries me and I want to guard against it (as it causes general problems on the server, rather than just isolated problems to the individual user). I want to know the most graceful way of handling this sort of problem.
The method I am calling is LocalReport.Render and this Google search shows a number of people with a number of problems where this method never seems to return.
Maybe try calling the method on a different Thread ? and abort the thread after a timeout ?
Although not a neat solution at all, but not a lot of options available in case there is no misconception about why the method hangs.
Having looked at this answer to a similar question I think the least worse solution is to wrap the offending call (to LocalReport.Render) into a separate Process and app domain. I will then kill the process if it starts behaving erratically.

Application hangs when calling external constructor -- troubleshooting steps?

This may be a long shot but I'm out of ideas.
I've got a VS C# solution with three projects in it. There's a class library project and then two application projects that depend on that class library. The class library in turn depends on a few other DLLs including the avalonedit dll from the sharpdevelop project.
One of the applications is building and running fine, including a use of my own control that wraps the avalonedit control. The other application is failing to run and it seems to be failing at the point when the avalonedit control is initialised via the XAML in my wrapping control.
The problem is that I don't see any errors in the debug output at all, all I see is the dll loaded message and then nothing. If I step into the constructor of my control the step never completes. The debugger says the app is running, but it is apparently spinning somewhere in the avalonedit dll when the underlying edit control is constructed by the XAML side.
I have to assume that there's some issue with difference in environment between the two projects but I'm kind of stumped as to how to proceed in tracking the problem down. Am I going to have to somehow get arrange matters so that I can put a break in the avalonedit source?
Edit: If I pause/break all it just drops back to the line calling my control constructor.
Sounds like a deadlock. Take a close look at all threads, their stack traces and synchronization primitives (locks, semaphores, etc.). Keep in mind: contended resources may not be explicit (for example, when you are inside static constructor waiting on something that tries to get access to a static field of the type being constructed you get a deadlock).
There are many ways to introduce a deadlock but no simple advice to handle it. You could also enable break on all exceptions in Visual Studio (Debug -> Exceptions... and tick CLR Exceptions).
If this does not help you could provide stack traces here and maybe somebody could spot the problem.

Determining the source of a thread

I've been experiencing a high degree of flicker and UI lag in a small application I've developed to test a component that I've written for one of our applications. Because the flicker and lag was taking place during idle time (when there should--seriously--be nothing going on), I decided to do some investigating. I noticed a few threads in the Threads window that I wasn't aware of (not entirely unexpected), but what caught my eye was one of the threads was set to Highest priority. This thread exists at the time Main() is called, even before any of my code executes. I've discovered that this thread appears to be present in every .NET application I write, even console applications.
Being the daring soul that I am, I decided to freeze the thread and see what happened. The flickering did indeed stop, but I experienced some oddness when it came to doing database interaction (I'm using SQL CE 3.5 SP1). My thought was that this might be the thread that the database is actually running on, but considering it's started at the time the application loads (before any references to the DB) and is present in other, non-database applications, I'm inclined to believe this isn't the case.
Because this thread (like a few others) shows up with no data in the Location column and no Call Stack listed if I switch to it in the debugger while paused, I tried matching the StartAddress property through GetCurrentProcess().Threads for the corresponding thread, but it falls outside all of the currently loaded modules address ranges.
Does anyone have any idea what this thread is, or how I might find out?
Edit
After doing some digging, it looks like the StartAddress is in kernel32.dll (based upon nearby memory contents). This leads me to think that this is just the standard system function used to start the thread, according to this page, which basically puts me back at square one as far as determining where this thread actually comes from. This is further confirmed by the fact that ALL of the threads in this list have the same value for StartAddress, leading me to ask exactly what the purpose is...?
Edit 2
Process Explorer let me to an actually meaningful start address. It looks like it's mscorwks.dll!CreateApplicationContext+0xbbef. This dll is in %WINDOWS%\Microsoft.NET\Framework\v2.0.50, so it looks like it's clearly a runtime assembly. I'm still not sure why
it's Highest priority
it appears to be causing hiccups in my application
You could try using Sysinternals. Process Explorer let's you dig in pretty deep. Right click on the Process to access Properties. Then "Threads" tab. In there, you can see the thread's stack and module.
EDIT:
After asking around some, it seems that your "Highest" priority thread is the Finalizer thread that runs due to a garbage collection. I still don't have a good reason as to why it would constantly keep running. Maybe you have some funky object lifetime behavior going on in your process?
I'm not sure what this is, but if you turn on unmanaged debugging, and set up Visual Studio with the Windows symbol server, you might get some more clues.
Might be the Garbage Collector thread. I noticed it too when I was once investigating a finalizer-related bug. Perhaps your system memory is low and the GC is trying to collect all the time? This was the case in the previously mentioned bug too. I couldn't reproduce it on my machine, but a co-worker of mine had a machine with less RAM where it would reappear like clockwork.

2nd call to Device.Reset in DirectX throws an InvalidCallException

I've been working on a DirectX application in C#, and I noticed that when I lock the workstation, the DirectX "Device" becomes lost. After looking up the information about what to do upon when a device is lost (and when a DeviceLostException is thrown by Device.Present), I re-wrote the code to reset the Device. This simply meant that I made a call to Device.Reset.
Calling Device.Reset recovered the Device. No problem. But when I lost the device a second time (for example, when the computer was locked, went to sleep, or activated a screen-saver), an exception was thrown by Device.Reset.
The exception was InvalidCallException, which (according to the documentation) means something went wrong with the call. So I assumed it was a problem with the arguments to the function. So instead of passing the same copy of PresentParams that I used to create the Device, I created a new instance of PresentParams (at first using the copy constructor, and later by re-creating without it) and passed that to Device.Reset.
Doesn't work. Device.Reset still dies with the InvalidCallException. Oh, and the message of the exception? "Error in application." Not helpful.
Can you point me in the direction of either a solution, or some documentation about how to get more debug information out of DirectX?
OK, I know how silly is seems to answer my own question, but I figured someone else might need this, eh?
The answer is: there were too many calls to the Dispose method of the VertexBuffers in the scene. The reason being that the internal Device reset-handlers were calling the Dispose method. And why was that happening? Because I had neglected to read the .NET DirectX SDK documentation regarding the Pool Enumeration, and was allocating the VertexBuffers using Pool.Default instead of Pool.Managed.
So obviously, after a few thousand badly done allocate-and-release cycles, something went wrong.
Oh, and how did I discover this? I attached a listener to VertexBuffer.Dispose which incremented a counter that I displayed on-screen. Imagine my suprise when I noticed this counter kept growing as I resized the window!

Categories

Resources