I'm trying to concatenate some data within a foreach iterator within a using block. Unfortunately, for some reason, any statements I insert into (or after) the using block after the foreach fail to fire.
Source:
static void sensor_DepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
{
using (var depthFrame = e.OpenDepthImageFrame())
{
if (depthFrame == null)
return;
short[] bits = new short[depthFrame.PixelDataLength];
string bitString = "0";
depthFrame.CopyPixelDataTo(bits);
foreach (var bit in bits)
{
bitString += bit.ToString();
Console.Write("This fires.");
}
Console.Write("This never fires and I don't know why.");
Program.Broadcast(bitString); //this also fails to fire.
}
Console.Write("This never fires either.");
}
Looking at the code there's no obvious reason for it not to work. I doubt it has anything to do with the using() block.
Maybe check the following:
Is your foreach loop terminating? How many elements are in the bits array and how many times is "This Fires" being written out?
The console output may be getting buffered and you aren't seeing anything printed until it is flushed. What happens if you replace Console.Write() with Console.WriteLine()?
The only other way execution could be breaking out of the loop without reaching Program.Broadcast(bitString) is if an exception is being thrown. Try wrapping the whole function in a try/catch/finally construct and print any exceptions that occur, and possibly a message in the finally block that should be printed no matter what happens.
Hope that helps.
Maybe the foreach takes too long? try using StringBuilder.
StringBuilder bitString = new StringBuilder("0");
depthFrame.CopyPixelDataTo(bits);
foreach (var bit in bits)
{
sb.Append(bit.ToString();
}
Program.Broadcast(bitString.ToString());
Related
I'm new to c# working with a windows service which has a timer but the autoreset is set to false so it supposed to run an infinite loop Querying to a Sql database. If the SQL returns records the process runs fine, but when no records are found the service throws an exception after 10 - 12 minutes, System.StackOverflowException was unhandled which is not clear (to me). Not sure how to better capture the issue or how to correct. Any assistance would be apprecieated.
`private static bool LoadRequests()
{
// check for requests will return combined Header/Detail record
bool RequestsLoaded = false;
string XMLURL = "";
string currentWorkingDirectory = "";
string text = "";
int rowcounter = 0;
try
{
//Summary List will be a subset of requested items, by ID#
var SummaryInfoList = new List<SummaryInfo>();
ReqHdrPlusDtlList myReqHdrPlusDetailList = new ReqHdrPlusDtlList();
List<ReqHdrPlusDtl> myReqHdrPlusDetailList = myReqHdrPlusDetailList.GetReqHdrPlusDtlList();
if (myReqHdrPlusDetailList != null && myReqHdrPlusDetailList.Count > 0)
{
// set check for last record
ReqHdrPlusDtl last = myReqHdrPlusDetailList.Last();
// scroll through each record in Request List
foreach (ReqHdrPlusDtl detailrec in myReqHdrPlusDetailList)
{
/// process id records ...
/// ...
} // exit for/each
}
else
{
//no records in list sleep for half a second before proceeding
Thread.Sleep(500);
text = "Done sleeping...";
WriteToAppLog(text);
}
//As soon as one request is fully processed, get the next pending record.
LoadRequests();
} // ends try
catch (Exception e)
{
WriteErrorMessageToAppLog(e);
RequestsLoaded = false;
}
return RequestsLoaded;
}`
When you look for the exception in the docs it states the following.
The exception that is thrown when the execution stack overflows because it contains too many nested method calls.
This exception often happens when you have an infinite loop, like in your code.
You are working with recursion (Recursion is an important programming technique that causes a function to call itself, source).
Because you keep calling your own function over and over again, you keep building up the stack, until it overflows.
You should rewrite the function so that it will actually end.
I suggest using a DispatcherTimer to call your function every 500ms, instead of Thread.Sleep() because Thread.Sleep() also blocks any execution of code on that thread.
private DispatcherTimer _dispatcherTimer;
private void SetUpTimer(){
_dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
_dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
_dispatcherTimer.Interval = TimeSpan.FromMilliseconds(500);
_dispatcherTimer.Start();
}
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
LoadRequests();
}
Note: I didn't test the code, and I haven't written c# in a while, though it should help you get there
You are using a recursive call which is causing the stack overflow problem. Get rid of the recursive call to correct. Possibly make a control loop as follows:
bool success = true;
while(success)
{
try
{
LoadRequests();
Thread.Sleep(500);
}
catch (exception ex)
{
//Log Error ex.Message;
success = false;
}
}
Once you eliminate calling the function inside of itself, the stack overflow problem should be resolved.
Edit
One other comment, is the recursion is never-ending (no control statement to block execution) which is a big no-no. If you have to use recursion then there must be a way to exit the method (a stop condition). All that being said, almost every recursive problem can be solved iteratively and it can be very beneficial to do so, as it consumes significantly less system resources. The above listed code would be an iterative solution.
Looping through a folder using system thread, how to ignore and continue if access to file was denied.
// Start thread.
System.Threading.ThreadStart start = delegate { scanner(#"C:\", "*.html;*.txt"); };
System.Threading.Thread thread = new System.Threading.Thread(start);
thread.Start();
private static string scanstatus = string.Empty;
private static void scanner(string folder, string patterns)
{
try
{
// Get the patterns.
string[] pattern_array = patterns.Split(';');
// Search.
foreach (string pattern in pattern_array)
{
foreach (string path in System.IO.Directory.GetFiles(folder, pattern, System.IO.SearchOption.AllDirectories))
{
// trim path
scanstatus = (path.Length > 60) ? "../" + path.Substring(path.Length - 59, 59) : path;
System.Threading.Thread.Sleep(5000);
}
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
finally
{
Console.WriteLine("*************DONE*************");
}
}
As Daniel mentioned in the comment, basically when you want to keep going with the next iteration, you need to move the try/catch to inside the loop. Currently your catch is outside the outer loop, so if an exception is thrown, execution can't continue. There's no concept of "continue from where you'd got to" within C#.
I'd strongly suggest that you also limit what you catch. For example:
foreach (string pattern in patternArray)
{
try
{
foreach (string path in Directory.GetFiles(...))
{
// ...
}
}
catch (IOException e)
{
// Log it or whatever
}
// Any other exceptions you want to catch?
}
Notes:
Catching Exception is almost always a bad idea, except as a final backstop at the top level of your request (or whatever) handling
Underscores in variable names aren't conventional in .NET; typically you'd use camelCase for variables (and PascalCase for methods, classes etc)
With using directives you can avoid putting the fully-qualified type names in your code, which would make it much easier to read
This method will end up being quite long - I'd suggest extracting the inner loop; possibly including the try/catch, or possibly not.
The following code is from MSDN:
private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();
private Dictionary<int, string> innerCache = new Dictionary<int, string>();
public void Add(int key, string value)
{
cacheLock.EnterWriteLock();
try
{
innerCache.Add(key, value);
}
finally
{
cacheLock.ExitWriteLock();
}
}
I've seen code like this in other places.The EnterWriteLock() is always outside the try block. Does anyone know why it's not inside the try block?
Suppose the EnterWriteLock() fails. For whatever reason.
Then the one thing you shouldn't do is to Exit a lock you never Entered.
It's a very basic pattern that also holds for example for streams, but not seen as often thanks to the using() {} statement.
var s = File.Create(...);
// (only) if the previous line succeeded,
// we gain the responsibility to close s, no matter what
try
{
// do some I/O
}
finally
{
s.Dispose();
}
Because that would be a bug. You can't call ExitWriteLock until you're sure that you entered it. Imagine what happens if you moved it inside try {} and EnterWriteLock() throws an exception. That's a double kaboom. Kabloom, screws up the exception message.
If EnterWriteLock throws an exception, there is no need to call ExitWriteLock, hence the reason it is not in the try block. ExitWriteLock should always be called if EnterWriteLock is successfully invoked. You may want to wrap a try block around EnterWriteLock in certain scenarios as it can throw a LockRecursionException. ExitWriteLock can also throw a SynchronizationLockException and may require a try block in your application.
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
What is the C# Using block and why should I use it?
My question: Is using using(a){do something with a} better than declaring 'a' and using it that way. ie: more secure, faster, ...
see examples for clarification.
Example 1:(without using)
StreamWriter sw;
string line;
sw = new StreamWriter("D:\\NewCon.xml");
sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
sw.WriteLine("<config>");
for (int i = 0; i >=36; i++)
{
line = "";
line = "<" + xmlnodes[i] + ">";
line += vals[i];
line += "</" + xmlnodes[i] + ">";
sw.WriteLine(line);
}
sw.WriteLine("</config>");
sw.Close();
sw.Dispose();
Example 2:(with using)
string line;
using (sw = new StreamWriter("D:\\NewCon.xml"))
{
sw.WriteLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>");
sw.WriteLine("<config>");
for (int i = 0; i >= 36; i++)
{
line = "";
line = "<" + xmlnodes[i] + ">";
line += vals[i];
line += "</" + xmlnodes[i] + ">";
sw.WriteLine(line);
}
sw.WriteLine("</config>");
}
using(a){do something with a}
This means that when the code block is done with a, the program will call a.Dispose. You know that even in the event of an exception, a will have Dispose called. It is essentially doing:
var a = IDisposable_Something;
try{.....}finally{a.Dispose();}
Is it more secure...not really, but that's not the point. The point of it is to make sure that resources which need to be cleaned up are done as soon as the program is finished with them.
So the problem with your first example, is that if somewhere along the line an exception is thrown, it won't make it to the Dispose() method. The second will. You always want to ensure Dispose gets called if it is there, because there is the possibility that the IDisposable classs won't have been written correctly, and it won't have the code to make sure that the unmanaged resources are cleaned up even if Dispose() isn't called (this is generally done in a finalizer). LInk to Dispose Pattern.
The only time I have ever seen where implementing using can be tricky is with the WCF service proxy (and you can work around that issue). There is a bug where if the proxy throws an exception at times, it will cause another exception in the Dispose() method.
http://blogs.msdn.com/b/jjameson/archive/2010/03/18/avoiding-problems-with-the-using-statement-and-wcf-service-proxies.aspx
Other than that you should generally try and put an IDisposable object in a using statement.
If an exception is thrown in your first example then the resource won't be disposed.
Using using ensures that the resource is disposed even when an exception is thrown.
Example 1 should never be done. If an exception is thrown, your Dispose() call will never happen, which could be bad. using guarantees execution of Dispose(). The only good alternative to Example 1 (besides using) would be:
var iDisposableObject = new YourDisposableConstructor();
try
{
// some code
}
finally
{
iDisposableObject.Dispose();
}
First of all, the code in example 1 should be wrapped in a try/finally block in order to be functionally equivalent with the code in example 2.
That said, I've always liked 'using' blocks for code like this. I think it generally leads to more readable code. As far as security or performance, you're not going to see much difference between example 1 and example 2, providing you use a try/finally block in the first example!
Using using is safer because you have guaranted resources releasing declared in using(...) braces even when any error or unexpected exit occured.
Added to previous answers, and the most importabt part, if an exception occurs, calling dispose() is guaranteed.
It's more secure in the sense that you tend not to forget to dispose of resources, especially in the case of an exception (your code currently doesn't catch any).
It's more succinct and idiomatic since you use less lines of code and the intend of your code becomes much clearer.
So this:
StreamWriter sw;
try
{
sw = new StreamWriter("D:\\epkDATA\\NewCon.xml");
...
}
finally
{
sw.Dispose();
}
is equivalent to:
using(StreamWriter sw = new StreamWriter("D:\\epkDATA\\NewCon.xml"))
{
...
}
if ClassA inherit from IDisposing.A "using" pattern is equal to following:
IDisposable iDisposableObject = new YourDisposableConstructor();
try
{
// some code
}
finally
{
iDisposableObject.Dispose();
}
so we'd better use the using pattern
I've noticed this problem happening a lot in most things I do, so I'm thinking there must be a design pattern for this.
Basically if an exception is thrown, attempt to solve the problem and retry. If I place it in the try, all it will do is catch the exception, but I want to retry whatever it was doing and if it fails again, retry again a certain number of times.
Is there a common pattern for this sort of stuff?
check this SO answer.. hope that helps u
Cleanest way to write retry logic?
public static class RetryUtility
{
public static void RetryAction(Action action, int numRetries, int retryTimeout)
{
if(action == null)
throw new ArgumenNullException("action");
do
{
try
{
action();
return;
}
catch
{
if(numRetries <= 0)
throw; // Avoid silent failure
else
{
Thread.Sleep(retryTimeout);
numRetries--;
}
}
}
while(numRetries > 0);
}
}
Call
RetryUtility.RetryAction( () => SomeFunctionThatCanFail(), 3, 1000 );
Credit goes to LBushkin
This runs indefinately but it would be easy to add a loop counter to the while clause
var solved = false;
var tries = 0;
while (!solved)
{
try
{
//Do Something
solved = true;
}
catch
{
//Fix error
}
finally
{
if(solved || IsRediculous(tries))
break;
tries++;
}
}
try/catch inside a loop, with a counter for retries?
EDIT: And your requirement of "retry whatever it was doing," you need custom logic for that, how to retry varies wildly (ie, reopen a stream, recreate the object, pause for X milliseconds, etc...), so you need it's own try/catch inside a loop for every atomic operation.
By "atomic operation" I mean a set of related statements, such as read a file. The whole file read into memory might be an atomic operation, for example.
On some limited basis, you might want to put your try/catch into a loop, and force break if is ultimately successful. Such might be for internet access testing and you want user to have another attempt at connection.
Something like this, maybe:
int MAX_RETRIES = 5;
for (var attempt=1; attempt <= MAX_RETRIES; attempt++) {
try {
DoSomethingThatMightThrow();
}
catch (AnExceptionIKnowHowToHandle) {
if (attempt < MAX_RETRIES)
continue;
throw;
}
}
Depends what you are trying, but typically you want to check for the possibility of an exception happening PRIOR to executing the code that could cause an exception.
For example, check that a file exists before accessing it, and create it (or whatever) if it doesn't.
Are you sure exception handling is the proper methodology here? If you can "solve the problem" you can probably detect the error condition prior to calling the exception-generatiing code.
Exception handling is most natural for things which are truly exceptional. A failed Internet connection (as in the previous answer) is something that can be detected and handled before calling exception-throwing code.
Yes, it is quite common to have a loop with a number of retries where you break out of the loop on success. A couple of things:
You might want to add a delay before retrying so that you don't use up all your retries in just a few milliseconds before the temporary problem had time to fix itself.
If you eventually fail, you should throw the first exception you caught, not the last one. The second exception could be the result of failing to recover correctly from the first failure and might not help to debug the original problem.
Coding what others have already mentioned:
var success = false;
var attempts = 0;
var maxAttempts = 0;
do {
attempts++;
try {
/* your code */
success = condition;
} catch(SuperciliousException e) {
/* recover */
}
} while(!success && attempts < maxAttempts);