What is the best way to return from a function that use using block? [duplicate] - c#

This question already has answers here:
What happens if i return before the end of using statement? Will the dispose be called?
(5 answers)
Closed 7 months ago.
What is the best way between those two implementations of using statement:
I wonder if the 2nd code prevent using from releasing the resource/ calling ondispose because of the return command?
1st code:
public byte[] DeriveSharedKey()
{
byte[] returnValue = null;
using (some resources)
{
some inner workings with resource...
returnValue = some_values;
}
return returnValue;
}
2nd code:
public byte[] DeriveSharedKey()
{
using (some resources)
{
some inner workings with resource...
return some_value;
}
}

The using statement will automatically call the Dispose method on the object once the program leaves the scope it's in, either way will work, the bottom one is just more compact.

Related

Used IDisposible for Object class but not returing the result to Ajax success in C# MVC [duplicate]

This question already exists:
Used IDisposible for Object class but not returing the result to Ajax success in c# [closed]
Closed 9 months ago.
In our application for the last few weeks we are getting memory exceptions.
W​herever we used DataSet & DataTable​, we used the Using Statement or Dispose method in Finally black.
For our Class objects not able to dispose of the stored values. In our class object we are storing large JSON strings from the database.
For this issue Microsoft recommended the IDisposable concept. We implement this concept in our class object.
So added the IDisposable in the class object and we are trying to call the Dispose method in Finally block. which is after returning the values to Jquery Ajax success method.
But In Ajax success method we didn't get the actual values from the controller. it is disposing the values before sending to the Jquery Ajax call.
Please find and below code and give your input.
ET_Reports dynamicGrid = new ET_Reports();
try
{
dynamicGrid = ReportAPI.GetDynamicReportGrid();
var jsonResult = Json(dynamicGrid, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
catch (Exception ex)
{
string strDisplayMsg = Log_Exception(ex);
return null;
}
finally
{
dynamicGrid.Dispose();
}
I think, you need to dispose dynamicGrid before return statement or replace return after finally statement. Any way you need to dispose before return.

How To Solve CA2202:To avoid generating a System.ObjectDisposedException Warning [duplicate]

This question already has answers here:
CA2202, how to solve this case
(12 answers)
Closed 7 years ago.
Every time on visual studio 2015, when i run Code Analysis, there are some annoying warnings. All of them are in a methods like this:
here is my method:
public static JObject ReadJson(string file_path)
{
try {
JObject o1 = JObject.Parse(File.ReadAllText(file_path));
using (StreamReader file = File.OpenText(file_path))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
return (JObject)JToken.ReadFrom(reader);//the warning is here
}
}
}
catch
{
return default(JObject);
}
}
so why this warning occur? How to solve it? And the most important is what
my fault in this method it seems to me very perfect
Warning Description
Severity Code Description Project File Line Warning CA2202 :
Microsoft.Usage : Object 'file' can be disposed more than once in
method 'JsonHelper.ReadJson(string)'. To avoid generating a
System.ObjectDisposedException you should not call Dispose more than
one time on an object.
MSDN:
Nested using statements (Using in Visual Basic) can cause violations
of the CA2202 warning. If the IDisposable resource of the nested inner
using statement contains the resource of the outer using statement,
the Dispose method of the nested resource releases the contained
resource. When this situation occurs, the Dispose method of the outer
using statement attempts to dispose its resource for a second time.
Problem:
using (StreamReader file = File.OpenText(file_path))
{
using (JsonTextReader reader = new JsonTextReader(file))
{
return (JObject)JToken.ReadFrom(reader);//the warning is here
} //"file" will be disposed here for first time when "reader" releases it
} //and here it will be disposed for the second time and will throw "ObjectDisposedException"
Solution:
You need to do it like this(disposing the object in finally block when all goes right, or in catch block when an error occurs):
public static JObject ReadJson(string file_path)
{
StreamReader file = null;
try {
JObject o1 = JObject.Parse(File.ReadAllText(file_path));
file = File.OpenText(file_path);
using (JsonTextReader reader = new JsonTextReader(file))
{
return (JObject)JToken.ReadFrom(reader);
}
}
catch
{
return default(JObject);
}
//dispose "file" when exiting the method
finally
{
if(file != null)
file.Dispose();
}
}

ASP.NET MVC5: The ObjectContext instance has been disposed [duplicate]

This question already has answers here:
Solving "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection" InvalidOperationException
(8 answers)
Closed 5 years ago.
I use asp.net mvc5 with EF, in this few string i received "The ObjectContext instance has been disposed and can no longer be used for operations that require a connection". What's wrong?
public JsonResult GetResponibleParty()
{
List<CI_ResponsibleParty> resParty;
using (MetabaseDbContext context = new MetabaseDbContext())
{
resParty = context.SetOfResponsibleParty.ToList();
return Json(resParty, JsonRequestBehavior.AllowGet);
}
}
Move your return statement after the using block. You have already created a list and held it in a variable.
public JsonResult GetResponibleParty()
{
List<CI_ResponsibleParty> resParty;
using (MetabaseDbContext context = new MetabaseDbContext())
{
resParty = context.SetOfResponsibleParty.ToList();
}
return Json(resParty, JsonRequestBehavior.AllowGet);
}
Solution found.
In this case me helped 2 methods:
1) context.Configuration.LazyLoadingEnabled = false;
2) or using .Include()

Will all objects created inline in a `using` statement be disposed of? [duplicate]

This question already has answers here:
Does the using statement dispose only the first variable it create?
(6 answers)
Closed 9 years ago.
This may be answered elsewhere, but after doing a bit of searching I didn't find much on the subject outside of the normal using context.
I am curious if all objects created in a using block will be disposed of as well as the original object.
Here is the context:
Normally I would do something like this:
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(commandText, conn))
{
//Do everything I need to here
}
I know that both conn and cmd go out of scope at this point and are disposed of because of the lovely using keyword.
I am curious if the same disposal rules would apply to the following statement:
using (var cmd = new (SqlCommand(commandText, new SqlConnection(ConnectionString)))
{
//Do everything I need here
}
Would the SqlConnection object that was created inline in the using statment be disposed of when cmd goes out of scope and is disposed of because it's associated with the object?
Also which would be syntactically preferred? I personally think the 2nd is cleaner, but I understand readability may come to play here as well.
For your second code, Dispose won't be called on SqlConnection instance when flow leaves using block unless SqlCommand.Dispose() do that internally (and no, it doesn't).
According to specification (8.13), using (ResourceType resource = expression) statement is transformed into:
{
ResourceType resource = expression;
try {
statement;
}
finally {
if(resource != null)
((IDisposable)resource).Dispose();
}
}
In your code, resource is SqlCommand, and that's the one Dispose is called on.
No.
using statements only apply to the resources declared directly in the statement; not to other allocations in the initializer.
You need a separate using statement for each resource.
According to MSDN, this code:
using (var temp = obj)
{
// ...
}
Translates to (including the extra curly braces to limit the scope):
{
var temp = obj;
try
{
// ...
}
finally
{
if (temp != null)
((IDisposable)temp).Dispose();
}
}
As you can see, if you substitute obj for new SqlCommand(commandText, new SqlConnection(ConnectionString)) then only the SqlCommand gets properly disposed.
{
SqlCommand temp = new SqlCommand(commandText,
new SqlConnection(ConnectionString));
try
{
// ...
}
finally
{
if (temp != null)
((IDisposable)temp).Dispose();
}
}
So, the SqlConnection won't get disposed unless the disposed SqlCommand does that. But it doesn't, and it shouldn't: it didn't create the object, therefore it must not destroy it either.
Certainly there are already answers that explains this correctly. This is covered by the specification as mentioned by others.
But you could just try it out. Here is an example:
static class Program
{
static void Main()
{
using (new DisposeMe("outer", new DisposeMe("inner", null)))
{
Console.WriteLine("inside using");
}
Console.WriteLine("after using scope");
}
}
class DisposeMe : IDisposable
{
public readonly string name;
public DisposeMe(string name, object dummy)
{
this.name = name;
}
public void Dispose()
{
Console.WriteLine("'Dispose' was called on instance named " + name);
}
}
Output:
inside using
'Dispose' was called on instance named outer
after using scope
(Of course if you nest two using statements, as in using (var inner = new DisposeMe("inner", null))
{
using (new DisposeMe("outer", inner))
{ ... } }, the Dispose method is called on both objects.)

Are there any circumstances under which the finally block does not get executed? [duplicate]

This question already has answers here:
Will code in a Finally statement fire if I return a value in a Try block?
(12 answers)
Does the C# "finally" block ALWAYS execute? [duplicate]
(11 answers)
Closed 9 years ago.
Please note this code:
class CTestFinally
{
public static void Run()
{
try
{
TryAndTry();
}
catch (Exception exError)
{
Console.WriteLine(exError.Message);
}
finally
{
Console.WriteLine("Finally...!");
}
Console.ReadKey();
}
static void TryAndTry()
{
try
{
TryAndTry();
}
catch (Exception exError)
{
Console.WriteLine(exError.Message);
}
finally
{
Console.WriteLine("Try: Finally...!");
}
}
}
}
Finally never executed because we get stack overflow Error.
Are there any circumstances under which the finally block does not get executed other than
above problem?
StackOverflowException is one of the few kinds of exception that a CLR host typically treats specially. ASP.NET will kill the worker process for example. This is very hard to debug because your app just goes away. SQL Server has similar policies I'm sure (like unloading the appdomain).
The reason for that is that this is a destabilizing condition that does not allow for reliable error recovery (after all your stack is unusable! You can for example not call your logger or send an email. There is no room on the stack.).
Another of this kind is OutOfMemoryException (you can't even allocate an Exception - that's why the CLR pre-allocates one OOM instance...). I think ASP.NET tolerates this while SQL Server kills your appdomain.
For normal exceptions this works fine.
This will never execute the finally:
using System;
namespace Demo
{
public static class Program
{
[STAThread]
public static void Main(string[] args)
{
try
{
Console.WriteLine("In try");
Environment.FailFast("Aaaaaargh");
}
finally
{
Console.WriteLine("In finally");
}
}
}
}

Categories

Resources