All Type Coding

Search Here

.Net Threading

Thread in computer science means a sequence of execution instructions that can run independently , that is a single flow of execution in a process. Thread is like a process, at least one thread exists within each process. Single Thread (normal programs) in computer science means that only one task can execute and at the same time the other tasks have to wait for the completion of the current task like in a queue. Single thread resulted in systems idle time and application performance.
In .Net, the threading is handled through the 'System.Threading' namespace. Creating a variable of the System.Threading.Thread type allows you to create a new thread to start working with. It allows you to create and access individual threads in a program.Creating Thread A thread is created by creating a Thread object, giving its constructor a ThreadStart reference.

ThreadStart childthreat = new ThreadStart(childthreadcall);

 

A simple classic thread Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart testThreadStart = new ThreadStart(new Program().testThread);
            Thread testThread = new Thread(testThreadStart);

            testThread.Start();
            Console.ReadLine();
        }

        public void testThread()
        {
            //executing in thread
            int count = 0;
            while (count++ < 50)
            {
                Console.WriteLine("Thread Executed "+count+" times");
                Thread.Sleep(500);
            }
        }
    }
}


Output: 








Multithreading allows multiple process to execute concurrently within a single program .That is more than one task in a program can execute at the same

time and each thread run independently of its own. If multiple threads can exist within a process, typically share the state information of a process, and

share memory and other resources directly. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to
save the thread context until it is scheduled.


Multithreaded Programming With Classic Threads:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadStart testThread1Start = new ThreadStart(new Program().testThread1);
            ThreadStart testThread2Start = new ThreadStart(new Program().testThread2);

            Thread[] testThread = new Thread[2];
            testThread[0] = new Thread(testThread1Start);
            testThread[1] = new Thread(testThread2Start);

            foreach (Thread myThread in testThread)
            {
                myThread.Start();
            }

            Console.ReadLine();
        }

        public void testThread1()
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 1 Executed "+count+" times");
                Thread.Sleep(1);
            }
        }

        public void testThread2()
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 2 Executed " + count + " times");
                Thread.Sleep(1);
            }
        }
    }
}
 

Output:











Working With ThreadPool: So, as we have seen so far in above code examples, uses ‘Thread’ in raw mode. However, we can simplify the thread running process with use of  ‘ThreadPool’ class that is provided by .NET framework and is very much helpful for quick implementation of multithreaded programming. All we have to do  is to queue the function we want running in thread. And it will automatically start executing them. The following code will demonstrate this simplified usage  of ‘ThreadPool’ .


For Example:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new Program().testThread1);
            ThreadPool.QueueUserWorkItem(new Program().testThread2);

            Console.ReadLine();
        }

        public void testThread1(Object threadContext)
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 1 Executed " + count + " times");
                Thread.Sleep(100);
            }
        }

        public void testThread2(Object threadContext)
        {
            //executing in thread
            int count = 0;
            while (count++ < 10)
            {
                Console.WriteLine("Thread 2 Executed " + count + " times");
                Thread.Sleep(100);
            }
        }
    }
}

Output:

















Thread Life Cycle:
The life cycle of a thread starts when an object of the System.Threading.Thread class is created and ends when the thread is terminated or completes execution.

Life cycle of a thread: The Unstarted State : It is the situation when the instance of the thread is created but the Start method is not called. The Ready State : It is the situation when the thread is ready to execute and waiting CPU cycle.    The Not Runnable State : a thread is not runnable, when:

Sleep method has been called
Wait method has been called
Blocked by I/O operations
The Dead State : It is the situation when the thread has completed execution or has been aborted.Thread Priority The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority.The priorities could be categorized as:

    Above normal
    Below normal
    Highest
    Lowest
    Normal

Once a thread is created, its priority is set using the Priority property of the thread class. 

NewThread.Priority = ThreadPriority.Lowest; 

.Net Garbage Collection

The garbage collection (GC) is new feature in Microsoft .net framework. it provides a new mechanism for releasing unreferenced objects from the memory (that is we no longer needed that objects in the program) ,this process is called Garbage Collection (GC). When it happens:
When a program creates an Object, the Object takes up the memory. Later when the program has no more references to that Object, the Object's memory becomes unreachable, but it is not immediately freed. The Garbage Collection checks to see if there are any Objects in the heap that are no longer being used by the application. If such Objects exist, then the memory used by these Objects can be reclaimed. So these unreferenced Objects should be removed from memory , then the other new Objects you create can find a place in the Heap.
The reclaimed Objects have to be Finalized later. Finalization allows a resource to clean up after itself when it is being collected. This releasing of unreferenced Objects is happening automatically in .Net languages by the Garbage Collector (GC). The programming languages like C++, programmers are responsible for allocating memory for Objects they created in the application and reclaiming the memory when that Object is no longer needed for the program. In .Net languages there is a facility that we can call Garbage Collector (GC) explicitly in the program by calling System.GC.Collect.

What is namespaces,.Net Application Domain and .Net Code Access Security.?

Namespaces are used to organize your code.it is the way to organize .NET Framework Class Library into a logical grouping according to their functionality, usability as well as category they should belong to, or we can say Namespaces are logical grouping of types for the purpose of identification.
 A good way to organize your namespaces is via a hierarchical system. You put the more general names at the top of the hierarchy and get more specific as you go down. This hierarchical system can be represented by nested namespaces.By placing code in different sub-namespaces, you can keep your code organized.

The example:

namespace india.CSharp.Namespaces
{
public class Hello
{
public string GetMessage()
{
return "Hello, world";
}
}
}

Namespaces are hierarchical, and the name india.CSharp.Namespaces is actually shorthand for defining  a namespace named arun that contains a namespace named CSharp that itself contains a namespace named Namespaces, as in:

namespace india
{
namespace CSharp
{
namespace Namespaces
{....}
}
}

The using keyword has two uses:

    Create an alias for a namespace (a using alias).
    Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).

Implement the "using" Directive
Next, we'll write a console application that uses the Hello class. We could just use the fully qualified name for the class-india.CSharp.Namespaces.Hello-but this name is quite long and unwieldy. An easier way is to use a "using" directive, which makes it possible to use all of the types in a namespace without qualification. If you would like to call methods without typing their fully qualified name, you can implement the "using"  directive.

using sysem;
using india.CSharp.Namespaces;
class Hello
{
static void Main()
{
Hello m = new Hello ();
System.Console.WriteLine(m.GetMessage());
}
}

"using System", is the same "using" directive you have seen in every program in this article. It allows you  to type the method names of members of the "System" namespace without typing the word "System" every time. In class Hello(), "Console" is a class member of the "System" namespace with the method "WriteLine". It's fully qualified name is "System.Console.WriteLine(...)".

Note that the two occurrences of Hello are shorthand for india.CSharp.Namespaces.Hello. C# also enables the definition and use of aliases. Such aliases can be useful in situation in which name collisions occur between two libraries, or when a small number of types from a much larger namespace are being used.

Using alias directives

A using-alias-directive introduces an identifier that serves as an alias for a namespace or type within the immediately enclosing compilation unit or namespace body.

using identifier = namespace-or-type-name ;

Within member declarations in a compilation unit or namespace body that contains a using-alias-directive, the identifier introduced by the using-alias-directive can be used to reference the given namespace or type.

For example:

namespace N1.N2
{
class A {}
}
namespace N3
{
using A = N1.N2.A;
class B: A {}
}

Here, within member declarations in the N3 namespace, A is an alias for N1.N2.A, and thus class N3.B
derives from class N1.N2.A. The same effect can be obtained by creating an alias R for N1.N2 and then
referencing R.A:

namespace N3
{
using R = N1.N2;
class B: R.A {}
}

The identifier of a using-alias-directive must be unique within the declaration space of the compilation unit or namespace that immediately contains the using-alias-directive.

Using namespace directives

A using-namespace-directive imports the types contained in a namespace into the immediately enclosing compilation unit or namespace body, enabling the identifier of each type to be used without qualification.

using-namespace-directive:using namespace-name ;

Within member declarations in compilation unit or namespace body that contains a using-namespace-directive, the types contained in the given namespace can be referenced directly.

For example:

namespace N1.N2
{
class A {}
}
namespace N3
{
using N1.N2;
class B: A {}
}

Here, within member declarations in the N3 namespace, the type members of N1.N2 are directly available, and thus class N3.B derives from class N1.N2.A. Like a using-alias-directive, a using-namespace-directive does not contribute any new members to the underlying declaration space of the compilation unit or namespace, but rather affects only the compilation unit or namespace body in which it appears.

The namespace-name referenced by a using-namespace-directive is resolved in the same way as the namespace-or-type-name referenced by a using-alias-directive. Thus, using-namespace-directives in the same compilation unit or namespace body do not affect each other and can be written in any order.

Conclusion:C# programs are organized using namespaces. Using directives are provided to facilitate the use of namespaces. From this article we can understand the need and usage of Namespaces in classes.The Namespaces can hold other types also as follows:
Classes,Structures,Interfaces,Enumerations,Delegates.Namespaces are used both as an "internal" organization system for a program, and as an "external" organization system-a way of presenting program elements that are exposed to other programs.


.Net Application Domain

An application domain is a virtual process and is used to isolate applications from one another. Each application domain has their own virtual address space which scopes the resources for the application domain using that address space.

Each application running within its main process boundaries and its application domain boundaries. All objects created within the same application scope are created within the same application domain. Multiple application domains can exist in a single operating system process. An application running inside one application domain cannot directly access the code running inside another application domain.

System.AppDomain is the main class you can use to deal with application domains.


.Net Code Access Security
The .NET Security Model provides code access permissions and code identity permissions. Code Access Security is the part of the .NET security model that determines whether or not the code is allowed to run, and what resources it can use when it is running. Code Access Security policy uses evidence to help grant the right permissions to the right assembly.

An administrator can configure Code Access Security policy to restrict the resource types that code can access and the other privileged operations it can perform. Code Access Security allows code to be trusted to varying degrees depending on where the code originates and on other aspects of the code's identity. Code Access Security can also help minimize the damage that can result from security vulnerabilities in your code.

What is Manifest,GAC (Global Assembly Cache), .Net Assembly Contents.?

Manifest is a file that containing Metadata about .NET Assemblies.
Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the
following things
• Version of assembly.
• Security identity.
• Scope of the assembly.
• Resolve references to resources and classes.
The assembly manifest can be stored in a PE file either (an .exe or) .dll with Microsoft
intermediate language (MSIL code with Microsoft intermediate language (MSIL) code or in a stand-alone PE file, that contains only assembly manifest information.


GAC (Global Assembly Cache) is where all shared .NET assembly reside.Each computer on which the Common Language Runtime is installed has a machine-wide code cache called the 'Global Assembly Cache'. The Global Assembly Cache (GAC) enables you to share assemblies across numerous applications. The GAC is automatically installed with the .NET runtime. The global assembly cache is located in 'Windows/WinNT' directory and inherits the directory's access control list that administrators have used to protect the folder.

The approach of having a specially controlled central repository addresses the shared library concept and helps to avoid pitfalls of other solutions that lead to drawbacks like DLL hell. The Global Assembly Cache Tool (Gacutil.exe), that allows you to view and manipulate the contents of the Global Assembly Cache.

.Net Assembly Contents

A .NET static assembly can consist of following elements:

a) Assembly Manifest - The Metadata that describes the assembly and its contents

b) Type Metadata - Defines all types, their properties and methods.

c) MSIL - Microsoft intermediate language

d) A set of Resources - All other resources like icons, images etc.Only the assembly manifest is required, but either types or resources are needed to give the assembly in any meaningful functionality.

Metadata in .Net

Metadata is the life blood of the .NET platform.it
is binary information which describes the characteristics of a resource . This information include Description of the Assembly , Data Types and members with their declarations and implementations, references to other types and members , Security permissions etc. A module's metadata contains everything that needed to interact with another module.
During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL) together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In Time (JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime loads metadata into memory and references it to discover information about your code's classes, members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition Language (IDL) files, header files, or any external method of component reference.

.Net Assembly

Assembly is a logical unit of code, that contains code which the Common Language Runtime (CLR) executes.Assembly is unit of deployment like EXE or a DLL. An assembly consists of one or more files (dlls, exe’s, html files etc.), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These
resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing. An assembly is completely self-describing. An assembly contains metadata information, which is used by the CLR for everything from type checking an security to actually invoking the components methods. As all information is in the assembly itself, it is independent of registry. This is the basic advantage as
compared to COM where the version was stored in registry.
 Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other. Assemblies can be private or shared. For private assembly deployment, the assembly is copied to the same directory as the client program that references it. No registration is needed, and no fancy installation program is required. When the
component is removed, no registry cleanup is needed, and no uninstall program is
required. Just delete it from the hard drive.  In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.


Types of Assembly:
There are two types of assembly
1- Private :A private assembly is normally
used by a single application, and is stored in the application's directory, or a sub-directory beneath.
2-and Public assembly.
A shared Assembly is one that can be referenced by more than one application. If multiple applications need to access an Assembly, we should add the Assembly to the Global Assembly Cache (GAC). There is also a third and least known type of an assembly: Satellite Assembly . A Satellite Assembly contains only static objects like images and other non-executable files required by the application.

Difference between NameSpace and Assembly?
A .Net Namespace provides the fundamental unit of logical code grouping while an assembly provides a fundamental unit of physical code grouping.
Namespace can span multiple assembly.

How to Add an assembly to GAC.?
    We can use Gacutil.exe to add strong-named assemblies to the global assembly cache.Type the following at the command prompt.

gacutil -i AssemblyName


AssemblyName name is the name of the assembly to install in the global assembly cache.We can use another option to install assembly in GAC by using Microsoft Windows Installer. This is the recommended and most common way to add assemblies to the global assembly cache.

How to remove an Assembly from GAC ?
At the command prompt type the following to remove the Assembly from GAC.

gacutil /u  AssemblyName (Fully Qualified Name of Assembly)
For Example

gacutil /u "assemblyname,Version=2.0.0.0, Culture=neutral, PublicKeyToken=0213456789ABCDEF"



How to see assembly version in c# .net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    public class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("The version of the currently executing assembly is: {0}",
                          typeof(Program).Assembly.GetName().Version);
            Console.ReadKey();
        }
    }
}
 

Output:
 


What is a Managed Code?

Managed Code in Microsoft .Net Framework, is the code to identify computer program source code that requires and will execute only under the management of a Common Language Runtime virtual machine.In short, all IL are
managed code. However, if you are using some third party software example VB6 or VC++
component they are unmanaged code, as .NET runtime (CLR) does not have control over the
source code execution of these languages.
Unmanaged code is compiled to machine code and therefore executed by the OS directly.
The benefits of Managed Code include programmers convenience and enhanced security . Managed code is designed to be more reliable and robust than unmanaged code , examples are Garbage Collection , Type Safety etc.