Friday, December 14, 2012

Synchronous and Asynchronous Calls with C#



/***********************************************************************
Synchronous(blocking) calls vs Asynchronous(non-blocking) calls with C#
***********************************************************************/


namespace Test { class Program { static void Add(int a, int b) { Console.WriteLine(a.ToString() + " + " + b.ToString() + " = " + (a + b).ToString()); } static void Mul(int a, int b) { Console.WriteLine(a.ToString() + " X " + b.ToString() + " = " + (a * b).ToString()); } static void Process() { int i; for (i = 0; i < 10; i++) { System.Threading.Thread.Sleep(1000); Console.WriteLine(i.ToString() + " "); } } static void Main(string[] args) { Add(3, 4); Process(); // assume that this will take long time to process some data Mul(2, 3); // this guy has to wait for Process() to complete though there is no dependency } } }
/***********************************************************************
To avoid the waiting situation for Mul(), just change the Main() as below
***********************************************************************/
delegate void ProcessDelegate(); static void Main(string[] args) { ProcessDelegate dlg = new ProcessDelegate(Process); Add(3, 4); IAsyncResult ar = dlg.BeginInvoke(null,null); // no callback after invoking Mul(2, 3); // no waiting for Process() to complete dlg.EndInvoke(ar); }

Tuesday, December 11, 2012

Simple Stored Procedure with C# & SQL

---------------------------------
EmpTable with 2 columns
--------------------------------
EmpID varchar(10)
EmpName varchar(50)

----------------------------------------
Stored Procedure:GetEmpName
-----------------------------------------
ALTER PROCEDURE [dbo].[GetEmpName](@EmpID varchar(10))
AS
BEGIN
               Select EmpName from EmpTable where EmpID = @EmpID
END

------------------------------------------------------------
Executing the above stored procedure with C#
-------------------------------------------------------------


// setup DB connection SqlConnection conn = new SqlConnection(ConnectionString);
// open the connection conn.Open();
// create command for executing the stored procedure SqlCommand cmd = new SqlCommand("GetEmpName", conn);
// set commnad type cmd.CommandType = CommandType.StoredProcedure;
// add parameter to stored procedure cmd.Parameters.Add(new SqlParameter("@EmpID", "ID001"));
// execute the command SqlDataReader rd = cmd.ExecuteReader();
// now you have EmpName for corresponding EmpID passed to the stored procedure
// close the connection conn.Close();