What is difference between this two C# methods - c#

What is the difference between these two cases. Firstly, if I open the connection and pass it into my method as a parameter, compared to opening the connection directly in the method?
cnn.open()
func(cnn,param1,param2);
vs
func(cnn, param1,param2)
{
cnn.open();
//open connection here
}

There's no difference from the code you've posted other than in one case, your calling function needs to take care of opening/closing the connection, in the other, you'd expect the function to do it.

The difference is that in the second method, you open the connection.
In the first method you expect the method to only use a connection not caring about cleaning up the resources.

No functional difference but the lines for opening and closing a connection should usually be as close together as possible hence they should be in the same method.

The difference is in how you want to use the connection and performance. If the function is a once off call and you are calling no other functions, or not doing anything else with the connection, then the second version of the function could even be reduced to:
func(param1, param2) {
Connection c = ....
c.Open(...);
...
c.Close();
}
However if you are calling many functions on the connection, even calling the function many times on the connection or if the creation and configuration of the connection is at a higher layer in your code, then you should use the first version of the function, with the addition of throwing an exception if the connection is not opened.

Well, I think you shouldn't ask for the different rather you should explain the situation you are in and ask for recommendation for what case must be used.
Anyway, As Everybody told you In case 2 the connection object and its life cycle is encapsulated within the callee function. This is recommended if database operation out side this function is not desired.
Otherwise if you have any other database activity to be done out side this function scope like in caller function or any other function(other than func) being called from caller function then you should use the Case 1.

Related

Is there any problem about create different Database contexts every time without using

Well, I would like to know what is the possible problems about use the following approach
CreateContextFactory().Create().QueryOpenConnectionCount();
instead of:
using (var context = CreateContextFactory().Create())
{
openConnectionCount = context.QueryOpenConnectionCount();
}
return openConnectionCount;
and also if there is any problem about something like:
CreateContextFactory().Create().QueryOpenConnectionCount1();
CreateContextFactory().Create().QueryOpenConnectionCount2();
CreateContextFactory().Create().QueryOpenConnectionCount3();
This is because I have some methods in a class that are open db contexts as above, I could create a using statement for them, but so I would need to pass the context for all methods, and I would also need to refactor a helper that executes a transaction using a db context (because it creates its own context internally). So what are the problems about let the code stay this way?
Often, a data-context "owns" a connection, to avoid constantly having to fetch one from the pool and initialize it. Disposing the data-context typically disposes that connection.
So: if you keep creating data-contexts without properly disposing them, you're hemorrhaging connections, at least until GC steps in and undoes the mess (releasing the unmanaged part of the connection back into the unmanaged pool, if there is an unmanaged part).
This is a bad thing, and severely limits scalability and increases the number of open connections to your database server. So yes, you should dispose your data-contexts. Extending that to the general case: you dispose any IDisposable thing that you're responsible for, when you're done with it. With perhaps a few exceptions (HttpClient, DataTable, etc).
Note that C# 8 has a slightly terser (I would say "nicer", but that is subjective; I like it a lot) syntax for this, if your using statement reaches to the end of the current scope (i.e. to the next }):
using var context = CreateContextFactory().Create();
return context.QueryOpenConnectionCount();
or even with earlier C# you can make it simpler and remove the local:
using (var context = CreateContextFactory().Create())
{
return context.QueryOpenConnectionCount();
}

Difference between a 'using statement' for every SqlConnection and single SqlConnection as private property in C# data layer

When implementing the repository pattern using Dapper ORM I am currently doing the following:
private readonly ConnectionStrings _connectionStrings;
private IDbConnection _db;
public CustomerRepository(IOptions<ConnectionStrings> connectionStrings)
{
_connectionStrings = connectionStrings.Value;
_db = new SqlConnection(_connectionStrings.DefaultConnection);
}
public Customer Find(int id)
{
return this._db.Query<Customer>("SELECT * FROM Contacts WHERE Id = #Id", new { id }).SingleOrDefault();
}
Can someone please tell me if I should be doing it this way or if I should be using a using statement with a new SqlConnection in every single repository function.
I am assuming my above code will need something like UnitOfWork to be effective right? And also some way of disposing the connection when done running all of the repository functions needed.
The recommended approach is to use using statements. User paulwhit explained their usage great in this answer:
The reason for the "using" statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.
The essential difference between having using statements in your methods and having the connection be a class member is that the using statement makes sure that once you're done with your operations, and have exited the block, your connection is closed and disposed of properly. This removes any possibility of error on the part of the developer, and generally makes everything neater.
An important additional benefit of the using statement in this situation is that it ensures the connection is disposed of, even if there is an exception (though it is worth noting that this isn't strictly the only way to achieve this). According to the documentation:
The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object.
If you were to have the connection be a class member, then an unhandled exception in the middle of a method that caused your program to exit early would possibly leave the connection open. This is of course not a good thing.
So to sum up, unless you have a very good reason not to, go with the using statement.
In general when a type implements IDisposable (and hence works with using) it can sometimes be useful to wrap it in another type, having that other type also implement IDisposable and have its Dispose() call the wrapped object, and then use using (or another mechanism to call Dispose()) on it.
The question is whether this is one of those sometimes.
It's not. In particular note that SqlConnection implements pooling behind the scenes, so (unless you explicitly opt-out in your connection string) instead of Dispose() shutting down the entire connection to the server what actually happens is that an object internal to the assembly of SqlConnection that handles the details of the connection is put into a pool to use again the next time an SqlConnection with the same connection string is opened.
This means that your application will get as efficient use of as few connections as possible over many uses of the SqlConnection class. But you are stymying that by keeping the connections out of the pool by not returning to the pool as promptly as possible.

Should a .Net/C# object call Dispose() on itself?

Below is some sample code written by a colleague. This seems obviously wrong to me but I wanted to check. Should an object call its own Dispose() method from within one of its own methods? It seems to me that only the owner/creator of the object should call Dispose() when it's done with the object and not the object itself.
It's an .asmx web method that calls Dispose() on itself when it's done. (The fact that it's a web method is probably incidental to the question in general.) In our code base we sometimes instantiate web service classes within methods of other web services and then call methods on them. If my code does that to call this method, the object is toast when the method returns and I can't really use the object any more.
[WebMethod]
public string MyWebMethod()
{
try
{
return doSomething();
}
catch(Exception exception)
{
return string.Empty;
}
finally
{
Dispose(true);
}
}
UPDATE:
Found a few links that are related:
Do I need to dispose a web service reference in ASP.NET?
Dispose a Web Service Proxy class?
For sure it's not a good prartice. The caller should decide when he is finished using the IDisposable object, not an object itself.
There are very few valid reasons to perform a "Self Disposing" action.
Threading is the one I use more than not.
I have several applications that "fire and forget" threads.
Using this methodology allow the object to self dispose.
This helps keep the environment clean without a threading manager process.
if I ever see that in one of my projects, I would ask why and I'm 99.9999% sure that i would remove it anyway
for me this is a kind of red flag / code smells
There are no technical restrictions on what a Dispose method is allowed to do. The only thing special about it is that Dispose gets called in certain constructs (foreach, using). Because of that, Dispose might reasonably be used to flag an object as no-longer-useable, especially if the call is idempotent.
I would not use it for this purpose however, because of the accepted semantics of Dispose. If I wanted to mark an object as no-longer-useable from within the class itself, then I would create a MarkUnuseable() method that could be called by Dispose or any other place.
By restricting the calls to Dispose to the commonly accepted patterns, you buy the ability to make changes to the Dispose methods in all of your classes with confidence that you will not unexpectedly break any code that deviates from the common pattern.
Just remove it, but take care to dispose it in all object that call it.
Technically yes, if that "method" is the finaliser and you are implementing the Finalise and IDisposable pattern as specified by Microsoft.
While a .Net object would not normally call Dispose on itself, there are times when code running within an object may be the last thing that expects to be using it. As a simple example, if a Dispose method can handle the cleanup of a partially-constructed object, it may be useful to have a constructor coded something like the following:
Sub New()
Dim OK As Boolean = False
Try
... do Stuff
OK = True
Finally
If Not OK Then Me.Dispose
End Try
End Sub
If the constructor is going to throw an exception without returning, then the partially-constructed object, which is slated for abandonment, will be the only thing that will ever have the information and impetus to do the necessary cleanup. If it doesn't take care of ensuring a timely Dispose, nothing else will.
With regard to your particular piece of code, the pattern is somewhat unusual, but it looks somewhat like the way a socket can get passed from one thread to another. There's a call which returns an array of bytes and invalidates a Socket; that array of bytes can be used in another thread to create a new Socket instance which takes over the communications stream established by the other Socket. Note that the data regarding the open socket is effectively an unmanaged resource, but it can't very well be wrapped in an object with a finalizer because it's often going to be handed off to something the garbage-collector can't see.
No! It is unexpected behavior and breaks the best practices guidelines. Never do anything that is unexpeceted. Your object should only do what is needed to maintain it's state while protecting the integrity of the object for the caller. The caller will decide when it's done (or the GC if nothing else).

Overhead of creating new SqlConnection in c#

A while back I wrote an ORM layer for my .net app where all database rows are represented by a subclass of DatabaseRecord. There are a number of methods like Load(), Save() etc. In my initial implementation I created a connection to the DB in the constructor of DatabaseRecord e.g.
connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["ConnectionName"].ConnectionString
);
I then call Open() and Close() on that SqlConnection at the beginning and end of my methods which access the database. This seemed to me (as someone who was familiar with programming but new to c# and .net) to be the most efficient way to do things - have one connection and open/ close it where necessary within the class.
I've just been doing some reading though and it appears that this pattern is recommended in a number of places:
using (var connection = new SqlConnection(...)) {
connection.Open();
// Stuff with the connection
connection.Close();
}
I can see why it's desirable - the connection is automatically Dispose()d even if the stuff you do in the middle causes an uncaught exception. I was just wondering what the overhead is for calling new SqlConnection() potentially many times like this.
Connection Pooling is on so I imagine the overhead is minimal and the second approach should be best practice but I just wanted to make sure my assumptions are right.
Yes, it is best practice. The using makes your call to Close() exception-safe.
And the overhead of creating a (any) object is indeed minimal, and smallest for short-lived objects (that stay in GC generation 0).
Note that you don't have to call Close() at the end of the using-block anymore, it is automatically done for you (Dispose==Close).
This is partially a matter of taste. As long as you employ connection pooling the overhead of creating a new (recycling a pooled connection) will be minimal, so generally the recommended pattern is to create new connection objects as needed.
If you run several commands immediately after each other then I see no reason to create new connections for each of them, but you should avoid holding on to open connections for a long time.
Also, you should note that the Dispose method will close the connection for you. So there is no need to call both Close and Dispose. Since the using clause will call dispose when it ends there is normally no need to call Close.
If you're unsure about the cost of opening/closing connection, have the SqlConnection a member variable of your class, but make the class IDisposable and dispose of the SqlConnection when the class is disposed

C# Question about thread safety

I'm using a threadpool to do some heavy processing and also bits of sql. Currently I open sql connections when I need them, run a query and then close them. This works fine. The application has been running with no issues. As more work is being done by this application it's using more threads. More threads mean more opening/closing of SQL connections. In SQL 2005 this actually hammers the server. My test server is doing around 175 transactions / sec. Approx 150 of these are being run in the master database and are "ValidateSQLLogin".
I'm going to change the app so that each thread has it's own connection and then this connection is passed around the thread.
So my question is:
If a SQL connection object is created locally in a thread and is then passed by ref to a static function of another class would this be unsafe?
void ThreadA()
{
SqlConnection a = new SqlConnection(....);
MyStaticClass.DoStuff(ref a);
}
void ThreadB()
{
SqlConnection b = new SqlConnection(....);
MyStaticClass.DoStuff(ref b);
}
static void MyStaticClass.DoStuff(ref SqlConnection sql)
{
// Do stuff with sql
}
My initial thought is that it would be unsafe as 10 threads could all call the same static function at the same time, each passing their own connection object.
Previously the static functions opened their own connections and closed them when they were done.
If it is unsafe whats the best method to work round this. I need to try and minimize open/close of Sql connections.
Thanks
Gareth
A parameter to a static function is not the same as a static field. Each execution of the static function will use different copy of the connection. You don't even need to have the parameter as reference (you need reference parameters only if you want to change them).
Each thread has it's own stack, and parameters and local variables are stored on the stack, so there is no problem having several threads calling the same static method. Each method call has it's own parameters and local variables.
There is no reason to pass the SqlConnection by reference to the method, though.
As said by others, calling a static method from multiple threads is not in itself a danger. However, if the static method modifies/accesses static fields* instead of just working with the parameters you pass it, you will need to make it thread-safe.
exception: some value types use atomic operations for access/writing and are implicitly thread-safe for those operations. However, race conditions may still occur in the logic that retrieves and updates these.
If you have that load of transactions I would recommend to keep one static connection, that remains open while you have this transactions, and when, the load greatly decreases or is null, it automatically closes, and with new requests it opens again.
Try the following:
You could use the lock statement to prevent other threads from entering the code block where you are using this connection, the other threads are automatically waiting till the previous thread is done and then enter this segment. Just make sure that the object you are locking is private to your static class.
In .Net all the static members are thread-safe.

Categories

Resources