Fast checking or limiting of thread memory usage in .NET?
I've seen some discussions similar to this question, but nothing that truly answers the issue I'm facing.
I'm working on a C# application where the software behavior can be customized through interpreted scripts. Each script is running on a different child thread of the C# app. (I'm using the Jint javascript interpreter to run the scripts, but my question is equally valid for any other circumstance under which a thread could behave dynamically in a .NET application). So far this is working great. But I need to ensure that the application behaves itself. In case of a bad script that could cause the application to run out of heap space, I need the ability to detect and stop any thread that is eating up too much memory. Conceptually, this could seen as similar to a web browser determining if javascript on a page is taking too long or too much memory to execute. The trouble is, I haven't been able to determine if there's any way to do such in .NET.
Is there some way I can either place a hard limit on the amount of memory a thread can utilize, or quickly check the thread's memory utilization from a parent thread? I'm not concerned with stack overflow within the thread, just heap space.
The "obviou开发者_如何学JAVAs" solution of course would be to split the interpreting into seperate processes rather than seperate threads, but that would incur a significant performance hit for my application since these scripts modify the software behavior and thus are intended to be tightly coupled. Application-level monitoring also wouldn't be ideal since it wouldn't provide information on which script isn't behaving itself. Also, a slow method meant for debugging won't work since the scripts are meant to allow for rapid modification of the software rather than having to build, test, and redeploy. I merely need some reasonably fast way to detect a thread that's eating too much memory so I can kill and ignore its script.
Thanks!
As other posters suggest, it may be easier to host in a separate process. A slightly lighter- weight approach would be to host in separate app domain and use the app-domain resource monitoring api to monitor memory usage.
WMI is one option for you. I know for certain that you can monitor process memory usage. But you can explore this idea more.
Here is small intro to WMI in C#. There is a whole set of classes that you can query. And for querying local machine stats, its not going to be very expensive. But I would recommend taking some performance numbers first.
精彩评论