Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Please let me know if the following design is bad for managing heap /memory and from a design pattern point of view also.
Here I am using a C# Timers.Timer on a windows service where the time tick event fires on multiple threads.
Here my main point is about heap memory consumption , since lots of objects being created in different threads in micro sec and also we cannot guarantee when GC will collect them. so this can be harmful to heap and performance issue later to the application.Am i correct.
timer_tick()
{
Test objTst=null;
try
{
objTst=new Test();
objTst.Process();
}
catch(execption e){}
finally
{
objTst =null;
}
}
Please let me know following design is bad for manage heap /memory wise and design pattern wise also.
This "pattern" serves no purpose. Setting the variable to null is not required. As soon as the method completes, and objTst goes out of scope, it will be eligible for garbage collection, even if you don't set it to null.
I would also recommend not having an empty exception handler that just swallows and ignores exceptions entirely. If nothing else, you should at least log the exception you receive.
In general, I would write this as:
private void timer_Tick(object sender, EventArgs e)
{
var tester = new Test();
tester.Process();
}
If you have an exception logging mechanism, you could wrap it in a try/catch to handle or log the exceptions, but don't just swallow them completely.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Is there any resources I can go to for tips on how to make a winForm with a long running operation?
My scenario is this. I have a WinForm that calls an API and stores data into a datagridview with multiple columns and about 10,000+ Rows.
I'm running multiple operations, such as counting distinct instances of a value in different columns and running a math operator to get a value. That application runs on about 2000 rows, but when I get to 4000, I get COM errors or other things stop it from executing.
I don't care if I have access to the UI, I just need the application to run.
Is there any resources I can go to for tips on how to make a winForm with a long running operation?
Sure, there are lots of resources for this sort of thing. You are more than likely looking for the BackgroundWorker. There is a great "code project" on it here.
public partial class Form1 : Form
{
BackgroundWorker backgroundWorker;
public Form1()
{
InitializeComponent();
backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += OnDoWork;
}
void OnDoWork(object sender, DoWorkEventArgs e)
{
// Long running code here.
}
}
The BackgroundWorker supports cancellation, and even reporting of progress. Additionally, there are several other key events you would want to implement.
Ideally, you will clean up and dispose of the object when your form is done using it - additionally, be sure to unwire event handlers as part of the cleanup. Here is another resource.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
The purpose of the interface IDisposable is to release unmanaged resources in an orderly fashion. It goes hand in hand with the using keyword that defines a scope after the end of which the resource in question is disposed of.
Because this meachnism is so neat, I've been repeatedly tempted to have classes implement IDisposable to be able to abuse this mechanism in ways it's not intended for. For example, one could implement classes to handle nested contexts like this:
class Context : IDisposable
{
// Put a new context onto the stack
public static void PushContext() { ... }
// Remove the topmost context from the stack
private static void PopContext() { ... }
// Retrieve the topmost context
public static Context CurrentContext { get { ... } }
// Disposing of a context pops it from the stack
public void Dispose()
{
PopContext();
}
}
Usage in calling code might look like this:
using (Context.PushContext())
{
DoContextualStuff(Context.CurrentContext);
} // <-- the context is popped upon leaving the block
(Please note that this is just an example and not to the topic of this question.)
The fact that Dispose() is called upon leaving the scope of the using statement can also be exploited to implement all sorts of things that depend on scope, e.g. timers. This could also be handled by using a try ... finally construct, but in that case the programmer would have to manually call some method (e.g. Context.Pop), which the using construct could do for thon.
This usage of IDisposable does not coincide with its intended purpose as stated in the documentation, yet the temptation persists.
Are there concrete reasons to illustrate that this is a bad idea and dispell my fantasies forever, for example complications with garbage collection, exception handling, etc. Or should I go ahead and indulge myself by abusing this language concept in this way?
So in asp.net MVC views, we see the following construct:
using(Html.BeginForm())
{
//some form elements
}
An abuse? Microsoft says no (indirectly).
If you have a construct that requires something to happen once you're done with it, IDisposable can often work out quite nicely. I've done this more than once.
"Is it an abuse of the IDisposable interface to use it this way"? Probably.
Does using using as a purely "scoping" construct make for more obvious intent and better readability of code? Certainly.
The latter trumps the former for me, so I say use it.
You certainly wouldn't be the first one to 'abuse' IDisposable in that way. Probably my favorite use of it is in timers, as the StatsD.NET client demonstrates:
using StatsdClient;
...
using (statsd.LogTiming( "site.db.fetchReport" ))
{
// do some work
}
// At this point your latency has been sent to the server
In fact, I'm pretty sure Microsoft themselves use it in some libraries. My rule of thumb would be - if it improves readbility, go for it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
this is a strange question.
In my work I use a software (that NO one can modify or take vision of source code), this software, unfortunately, is very bad. It uses, when launched, about 1 gb RAM, but running and being used, it accumulates data in ram and after few hours it occupies over 4gb of ram, and can accumulates more and more if not stopped. Since not all pc of my company can handle this, they crash. Is there a way to clear data unused in ram from other software programming in c#?
I just need an hint, i program in c#.
I'm sorry for my English, and if this question is somehow wrong.
Thanks for time.
Edit: I will add some information about this software understand better what I can do, and what I cant't.
Since i would not gain anything hacking this software, but I would have a better life (and not only me but my co-workers and employees too), i don't see any issue in hacking this software. (well, my chief has no problems, and his chief too).
I will try the Arunasr hint, I program in c# and know this function. I will only have to decompile it.
I have to delete this question?
Thanks for all replies and all help you gave to me.
There is no such way, outside of killing and restarting that task. If it is a Windows Service, you can use Powershell, command line utility SC.exe, or this c# code:
public static void RestartService(string serviceName, int timeoutMilliseconds)
{
ServiceController service = new ServiceController(serviceName);
try
{
int millisec1 = Environment.TickCount;
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
// count the rest of the timeout
int millisec2 = Environment.TickCount;
timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2-millisec1));
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running, timeout);
}
catch
{
// ...
}
}
Reference: http://www.csharp-examples.net/restart-windows-service/
.NET runtime garbage collector tends to be lazy and only collects when free memory is about to run out. You can force garbage collection with GC.Collect(), but mind the performance: it is expensive if you do it frequently.
If the library really accumulates data (i.e. data remains references and GC cannot touch it), there is little you can do other than hack up the library, figure out what eats up the memory and release the unnecessary objects. It is not difficult to decompile the .NET bytecode. In the extreme, you can modify the assembly bytecode using reflection after it has been loaded. I would not recommend it unless you are desperate.
You can use GC to track real memory usage stats.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Does this method use plenty of my memory resources?
Private MyWorkerClass worker;
Private Thread myWorkerThread;
//private Thread myWorkerThread= new Thread(worker.doThisWork); // i cant do this, because i cant restart the thread when i construct it here.
public void IwantMyWorkDosomething(){
myWorkerThread= new Thread(worker.doThisWork);
myWorkerThread.start();
myWorkerThread.stopWorking(); // stop my worker class thread running;
}
public void main(){
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
this.IwantMyWorkDosomething();
}
my Code is working, but i am not sure whether it gonna crash my program if i run the method 1000 times.
Constructing a thread object is cheap. Also, re-constructing a new one is cheap. The garbage collector will free the unused resources, you just need to make sure you're not unnessecarilly keeping references to finished thread objects.
What could become a resource problem is only when you try to run thousands of threads at the same time. But even then, it's not the memory that will usually cause the bottleneck but the CPU and the task scheduler (i.e the tasks will start to run slower than exected).
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I am working in a code-base(C# 3.5), which is littered with exception handling blocks which return true/false, when inside in a function which returns 'bool'.
catch (Exception ex) { return false; }
This is not correct practice.I am thinking of logging the exception, and have a local variable(to function) which will be initialized.And, this variable will be returned at the end of function.
What do you think?
The usual accepted way to handle exception is to handle them only if you can do something about it. You can of course handle a generic exception just for log puroposes but you should reraise it once you're done.
Your application logic shouldn't rely on exceptions. If there is absolutely no other way to do it, then at least handle concrete exceptions instead of the generic one...
Personally, I would get rid of all of these catch blocks and let the exception bubble up when it happens.
As you say, using exceptions for application logic is bad practice.
Have a catchall exception handler that will catch all such exceptions and log them and terminate the program (if that's the right thing for this program).
It is highly subjective what you want here.
It is old C-style code to have your functions return a true/false value depending on the function succeding or not. In the C# world, it is alot more common to throw exceptions.
You can debate for a long time which is the right path to choose for your code base.
My general point of view is to stick to the exceptions, they have the advantage that they bubble up and usually require less code. And there is also great support for actually logging uncaught exceptions.
You inherited code where the original programmer just didn't want to deal with errors. As written, the program will simply malfunction (say, not save a record to the database) and there's no way to find out why it malfunctioned. Especially since this is dbase code, this will cause random data corruption and loss of precious data.
You indeed cannot leave the code the way it is. The very first thing you need to do is remove all try/catch statements so the program terminates when there's an error. Add an AppDomain.UnhandledException event handler to log the exception so you know what went wrong. Fix errors you'll encounter by correcting code or validating the data. Do expect this to take time, it is very likely that you'll discover many design problems that were shoved under a doormat before.
That's certainly better than what you've got!
Although I wouldn't recommend using the bool return value as proper exception handling, if there is already a lot of code written that way, going and making sweeping modifications everywhere may not be the best idea.
Throwing an exception is generally better than returning false - an exception can at least give the receiver some clue of what happened and why the failure occurred.
The return value of a method should be the result of a method, or it should throw an exception explaining why the requested operation could not be completed.