I am under Visual Studio 2010 in a Windows Application Project with framework 4. So to achieve your need you right click on My Project Folder and click open. Under Application tab (the default one) click on the latest button View Application Events. This will create an ApplicationEvents class. Open it and copy paste this code :
Public Sub My_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException
AddHandler System.Windows.Forms.Application.ThreadException, AddressOf UIThreadException
End Sub
Private Sub UIThreadException(ByVal sender As Object, ByVal ex As ThreadExceptionEventArgs)
Try
WriteErrorLog(ex.Exception)
Catch
Finally
End Try
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
' NOTE: This exception cannot be kept from terminating the application - it can only
' log the event, and inform the user about it.
Private Sub CurrentDomain_UnhandledException(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs)
Try
Dim ex As Exception = CType(e.ExceptionObject, Exception)
WriteErrorLog(ex)
Catch exc As Exception
End Try
End Sub
From method:
WriteErrorLog(ByVal ex As Exception)
You can create your own method to log the error. Note that you do not need of :
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic)
At all and even less turning off the application framework.
Hope this will help someone.
dalkar69
Friday, April 29, 2011
Catch Exception in VS2010
I am under Visual Studio 2010 in a Windows Application Project with framework 4. So to achieve your need you right click on My Project Folder and click open. Under Application tab (the default one) click on the latest button View Application Events. This will create an ApplicationEvents class. Open it and copy paste this code :
Public Sub My_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException
AddHandler System.Windows.Forms.Application.ThreadException, AddressOf UIThreadException
End Sub
Private Sub UIThreadException(ByVal sender As Object, ByVal ex As ThreadExceptionEventArgs)
Try
WriteErrorLog(ex.Exception)
Catch
Finally
End Try
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
' NOTE: This exception cannot be kept from terminating the application - it can only
' log the event, and inform the user about it.
Private Sub CurrentDomain_UnhandledException(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs)
Try
Dim ex As Exception = CType(e.ExceptionObject, Exception)
WriteErrorLog(ex)
Catch exc As Exception
End Try
End Sub
From method:
WriteErrorLog(ByVal ex As Exception)
You can create your own method to log the error. Note that you do not need of :
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic)
At all and even less turning off the application framework.
Hope this will help someone.
dalkar69
Public Sub My_Startup(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupEventArgs) Handles Me.Startup
AddHandler AppDomain.CurrentDomain.UnhandledException, AddressOf CurrentDomain_UnhandledException
AddHandler System.Windows.Forms.Application.ThreadException, AddressOf UIThreadException
End Sub
Private Sub UIThreadException(ByVal sender As Object, ByVal ex As ThreadExceptionEventArgs)
Try
WriteErrorLog(ex.Exception)
Catch
Finally
End Try
End Sub
' Handle the UI exceptions by showing a dialog box, and asking the user whether
' or not they wish to abort execution.
' NOTE: This exception cannot be kept from terminating the application - it can only
' log the event, and inform the user about it.
Private Sub CurrentDomain_UnhandledException(ByVal sender As Object, ByVal e As System.UnhandledExceptionEventArgs)
Try
Dim ex As Exception = CType(e.ExceptionObject, Exception)
WriteErrorLog(ex)
Catch exc As Exception
End Try
End Sub
From method:
WriteErrorLog(ByVal ex As Exception)
You can create your own method to log the error. Note that you do not need of :
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic)
At all and even less turning off the application framework.
Hope this will help someone.
dalkar69
Monday, April 25, 2011
How to debug a hang process
http://blogs.msdn.com/b/kirillosenkov/archive/2008/12/07/how-to-debug-crashes-and-hangs.aspx
How to debug crashes and hangs
At my job on the C# IDE QA team I've learned some useful things about debugging in Visual Studio, which I'd like to summarize in this post. Although the screenshots were made using Visual Studio 2008 SP1, this pretty much applies to other versions of VS as well.
Rich debugging support
When you develop your C# application and hit F5, the target process (your program) gets started, and then the Visual Studio process attaches the debugger to the process where your code is running. This way, you can break into the debugger and VS will provide you with all sorts of rich debugging support - current statement highlighting, call stack, watches, locals, immediate window, Edit-and-Continue and so on.
More importantly, if your application throws an exception or crashes, the debugger will intercept that and provide your with all the information about the exception.
As a side note, in Visual Studio there is a way to run your code without attaching the debugger - the shortcut is Ctrl+F5. Try throwing an exception in your code when using F5 and Ctrl+F5 to feel the difference.
throw null;
By the way, my favorite way to artificially throw exceptions is throw null; I just love the fact that it throws a NullReferenceException because it can't find the exception object and nevertheless does exactly what I want it to do :)
Crashes and the Watson dialog
What if a program crashes or throws an exception, which you don't have source code for? Moreover, you didn't start the program using F5, but the operating system launched the process. I remember that before coming to Microsoft, the only thing I could do about some application crashing was to express my disappointment about the fact (usually in Russian). Now I don't feel helpless anymore, because I've learned a couple of tricks. As an example for this we'll crash Visual Studio itself and then debug the crash.
How to crash Visual Studio?
Viacheslav Ivanov reported an interesting crashing bug in our language service recently. Save all your work and then paste this code in a C# Console Application and change 'object' to 'int':
using System;
static class Program
{
static void Main()
{
ITest
How to debug crashes and hangs
At my job on the C# IDE QA team I've learned some useful things about debugging in Visual Studio, which I'd like to summarize in this post. Although the screenshots were made using Visual Studio 2008 SP1, this pretty much applies to other versions of VS as well.
Rich debugging support
When you develop your C# application and hit F5, the target process (your program) gets started, and then the Visual Studio process attaches the debugger to the process where your code is running. This way, you can break into the debugger and VS will provide you with all sorts of rich debugging support - current statement highlighting, call stack, watches, locals, immediate window, Edit-and-Continue and so on.
More importantly, if your application throws an exception or crashes, the debugger will intercept that and provide your with all the information about the exception.
As a side note, in Visual Studio there is a way to run your code without attaching the debugger - the shortcut is Ctrl+F5. Try throwing an exception in your code when using F5 and Ctrl+F5 to feel the difference.
throw null;
By the way, my favorite way to artificially throw exceptions is throw null; I just love the fact that it throws a NullReferenceException because it can't find the exception object and nevertheless does exactly what I want it to do :)
Crashes and the Watson dialog
What if a program crashes or throws an exception, which you don't have source code for? Moreover, you didn't start the program using F5, but the operating system launched the process. I remember that before coming to Microsoft, the only thing I could do about some application crashing was to express my disappointment about the fact (usually in Russian). Now I don't feel helpless anymore, because I've learned a couple of tricks. As an example for this we'll crash Visual Studio itself and then debug the crash.
How to crash Visual Studio?
Viacheslav Ivanov reported an interesting crashing bug in our language service recently. Save all your work and then paste this code in a C# Console Application and change 'object' to 'int':
using System;
static class Program
{
static void Main()
{
ITest
Sunday, April 24, 2011
Create new usergroup from command line
Copied from
http://www.windows-commandline.com/2009/05/add-user-to-group-from-command-line.html
On Windows computer we can add users to a group from command line too. We can use net localgroup command for this.
net localgroup group_name UserLoginName /add
For example to add a user to administrators group from command line we can run the below command. In the below example I have taken username as John.
net localgroup administrators John /add
Few more examples:
To add a domain user to local users group from command line:
net localgroup users domainname\username /add
This command should be run when the computer is connected to the network. Otherwise you will get the below error.
H:\>net localgroup users domain\user /add
System error 1789 has occurred.
The trust relationship between this workstation and the primary domain failed.
To add a domain user to local administrator group from command line:
net localgroup administrators domainname\username /add
To add a user to remote desktop users group:
net localgroup "Remote Desktop Users" UserLoginName /add
To add a user to debugger users group:
net localgroup "Debugger users" UserLoginName /add
To add a user to Power users group:
net localgroup "Power users" UserLoginName /add
This command works on all editions of Windows OS i.e Windows 2000, Windows XP, Windows Server 2003, Windows Vista and Windows 7. In Vista and Windows 7, even if you run the above command from administrator login you may still get access denied error like below.
C:\> net localgroup administrators techblogger /add
System error 5 has occurred.
Access is denied.
The solution for this is to run the command from elevated administrator account. See How to open elevated administrator command prompt
When you run the 'net localgroup' command from elevated command prompt:
C:\Windows\system32>net localgroup administrators techblogger /add
The command completed successfully.
To list the users belonging to a particular group we can run the below command.
net localgroup group_name
For example to list all the users belonging to administrators group we need to run the below command.
net localgroup administrators
http://www.windows-commandline.com/2009/05/add-user-to-group-from-command-line.html
On Windows computer we can add users to a group from command line too. We can use net localgroup command for this.
net localgroup group_name UserLoginName /add
For example to add a user to administrators group from command line we can run the below command. In the below example I have taken username as John.
net localgroup administrators John /add
Few more examples:
To add a domain user to local users group from command line:
net localgroup users domainname\username /add
This command should be run when the computer is connected to the network. Otherwise you will get the below error.
H:\>net localgroup users domain\user /add
System error 1789 has occurred.
The trust relationship between this workstation and the primary domain failed.
To add a domain user to local administrator group from command line:
net localgroup administrators domainname\username /add
To add a user to remote desktop users group:
net localgroup "Remote Desktop Users" UserLoginName /add
To add a user to debugger users group:
net localgroup "Debugger users" UserLoginName /add
To add a user to Power users group:
net localgroup "Power users" UserLoginName /add
This command works on all editions of Windows OS i.e Windows 2000, Windows XP, Windows Server 2003, Windows Vista and Windows 7. In Vista and Windows 7, even if you run the above command from administrator login you may still get access denied error like below.
C:\> net localgroup administrators techblogger /add
System error 5 has occurred.
Access is denied.
The solution for this is to run the command from elevated administrator account. See How to open elevated administrator command prompt
When you run the 'net localgroup' command from elevated command prompt:
C:\Windows\system32>net localgroup administrators techblogger /add
The command completed successfully.
To list the users belonging to a particular group we can run the below command.
net localgroup group_name
For example to list all the users belonging to administrators group we need to run the below command.
net localgroup administrators
Sleep command
In QMSL QPHONEMS/user defined transport, we use sleep(1) in worker thread to pull data from virtual COM ports. However, this “Sleep(1)” doesn’t really yield 1ms to other thread to execute. In fact, it yields close to 15ms. This symptom was observed in different incidents
1. Adnan’s station will take 10 mins to program LCU when “Sleep()” is used to control to data flow into the device. Other machines will take 3 mins
2. Foxconn’s machine takes 133 seconds to backup NVs with QPHONEMS. The same QMSL APIs running with QPST takes 20. This issue was later reproduced with QRD2 and QDART1.
It turns out that the default clock res, which is 15.625ms, affects the sleep behavior in OS.
You can download the tool from
http://technet.microsoft.com/en-us/sysinternals/bb897568.aspx
to check the clock res.
The slow machine has a clock resolution of 15.625ms. The normal machine has a clock resolution of 0.977ms (1/16 clock of 15.625). These slow machines usually don’t have much software installed. I guess some software, such as GPIB driver, running in background changes the default resolution to 0.977ms. In which, Sleep(1) will yield close to 1ms.
It turns out that there is undocumented API to change the clock resolution. The API is called “NtSetTimerReolution” in NTDLL.dll
http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/Time/NtSetTimerResolution.html
Once I call the API outside QMSL, all the problems were solved.
I plan to make some changes to QMSL worker thread.
1. Incorporate “NtSetTimerReoution” before worker thread is started
2. Expose new QMSL API to configure how often the worker thread goes to sleep. Currently, it sleep at each iteration. It takes 22 sec to backup NV in QPST mode. It takes 27s in QPHONEMS. Reducing the sleep frequency will speed up QHONEMS performance at the cost CPU usage. The default will still be Sleep(1) per iteration. The performance delta will be realized in 1) NON-Signaling test, 2) GPS I/Q capture, 3) NV backup/restore.
1. Adnan’s station will take 10 mins to program LCU when “Sleep()” is used to control to data flow into the device. Other machines will take 3 mins
2. Foxconn’s machine takes 133 seconds to backup NVs with QPHONEMS. The same QMSL APIs running with QPST takes 20. This issue was later reproduced with QRD2 and QDART1.
It turns out that the default clock res, which is 15.625ms, affects the sleep behavior in OS.
You can download the tool from
http://technet.microsoft.com/en-us/sysinternals/bb897568.aspx
to check the clock res.
The slow machine has a clock resolution of 15.625ms. The normal machine has a clock resolution of 0.977ms (1/16 clock of 15.625). These slow machines usually don’t have much software installed. I guess some software, such as GPIB driver, running in background changes the default resolution to 0.977ms. In which, Sleep(1) will yield close to 1ms.
It turns out that there is undocumented API to change the clock resolution. The API is called “NtSetTimerReolution” in NTDLL.dll
http://undocumented.ntinternals.net/UserMode/Undocumented%20Functions/Time/NtSetTimerResolution.html
Once I call the API outside QMSL, all the problems were solved.
I plan to make some changes to QMSL worker thread.
1. Incorporate “NtSetTimerReoution” before worker thread is started
2. Expose new QMSL API to configure how often the worker thread goes to sleep. Currently, it sleep at each iteration. It takes 22 sec to backup NV in QPST mode. It takes 27s in QPHONEMS. Reducing the sleep frequency will speed up QHONEMS performance at the cost CPU usage. The default will still be Sleep(1) per iteration. The performance delta will be realized in 1) NON-Signaling test, 2) GPS I/Q capture, 3) NV backup/restore.
Monday, April 18, 2011
Threading
http://msdn.microsoft.com/en-us/library/system.threading.thread.start.aspx
When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.
You can use the WaitHandle.WaitOne method to request ownership of a mutex. The thread that owns a mutex can request the same mutex in repeated calls to WaitOne without blocking its execution. However, the thread must call the ReleaseMutex method the same number of times to release ownership of the mutex. The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity.
If a thread terminates while owning a mutex, the mutex is said to be abandoned. The state of the mutex is set to signaled, and the next waiting thread gets ownership. Beginning in version 2.0 of the .NET Framework, an AbandonedMutexException is thrown in the next thread that acquires the abandoned mutex. Before version 2.0 of the .NET Framework, no exception was thrown.
Mutexes are of two types: local mutexes, which are unnamed, and named system mutexes. A local mutex exists only within your process. It can be used by any thread in your process that has a reference to the Mutex object that represents the mutex. Each unnamed Mutex object represents a separate local mutex.
Named system mutexes are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create a Mutex object that represents a named system mutex by using a constructor that accepts a name. The operating-system object can be created at the same time, or it can exist before the creation of the Mutex object. You can create multiple Mutex objects that represent the same named system mutex, and you can use the OpenExisting method to open an existing named system mutex.
When two or more threads need to access a shared resource at the same time, the system needs a synchronization mechanism to ensure that only one thread at a time uses the resource. Mutex is a synchronization primitive that grants exclusive access to the shared resource to only one thread. If a thread acquires a mutex, the second thread that wants to acquire that mutex is suspended until the first thread releases the mutex.
You can use the WaitHandle.WaitOne method to request ownership of a mutex. The thread that owns a mutex can request the same mutex in repeated calls to WaitOne without blocking its execution. However, the thread must call the ReleaseMutex method the same number of times to release ownership of the mutex. The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity.
If a thread terminates while owning a mutex, the mutex is said to be abandoned. The state of the mutex is set to signaled, and the next waiting thread gets ownership. Beginning in version 2.0 of the .NET Framework, an AbandonedMutexException is thrown in the next thread that acquires the abandoned mutex. Before version 2.0 of the .NET Framework, no exception was thrown.
Mutexes are of two types: local mutexes, which are unnamed, and named system mutexes. A local mutex exists only within your process. It can be used by any thread in your process that has a reference to the Mutex object that represents the mutex. Each unnamed Mutex object represents a separate local mutex.
Named system mutexes are visible throughout the operating system, and can be used to synchronize the activities of processes. You can create a Mutex object that represents a named system mutex by using a constructor that accepts a name. The operating-system object can be created at the same time, or it can exist before the creation of the Mutex object. You can create multiple Mutex objects that represent the same named system mutex, and you can use the OpenExisting method to open an existing named system mutex.
Friday, April 8, 2011
ShutDown remote desktop
here are 10 ways to get the option to Shutdown or Restart a Remote Desktop:
1. Press CTRL+ALT+END to get to the Task Manager, and then click Shutdown (apparently does not always work).
2. Press CTRL+SHIFT+ESC to get to the Task Manager.
3. Right click on the TaskBar and select the Task Manager.
4. For the Classic Start Menu, left click on Start, Settings, Windows Security to get to the Task Manager.
5. For the "new" Start Menu, left click on Start, Windows Security to get to the Task Manager.
6. Create a shortcut to the Task Manager (usually located at C:/WINDOWS/system32/taskmgr.exe) and put it on the desktop or taskbar [my own solution before I found this site]
7. Click Start, Run, type "shutdown -i" (without the quotes), click OK, to get a GUI that apparently doesn't use the Task Manager (this seems to require that Directory Services be running so as to be able to browse for the computer to shut down, or you must manually add the name of the remote computer to be shut down).
8. Click Start, Run, type "shutdown -r -t xx" (without the quotes) [xx=how many xx seconds to execute this command], click OK (I've not tried this myself).
9: Click on a blank area of the desktop or taskbar, press Alt-F4, and the standard Stand By, Turn Off, Restart dialog appears.
1. Press CTRL+ALT+END to get to the Task Manager, and then click Shutdown (apparently does not always work).
2. Press CTRL+SHIFT+ESC to get to the Task Manager.
3. Right click on the TaskBar and select the Task Manager.
4. For the Classic Start Menu, left click on Start, Settings, Windows Security to get to the Task Manager.
5. For the "new" Start Menu, left click on Start, Windows Security to get to the Task Manager.
6. Create a shortcut to the Task Manager (usually located at C:/WINDOWS/system32/taskmgr.exe) and put it on the desktop or taskbar [my own solution before I found this site]
7. Click Start, Run, type "shutdown -i" (without the quotes), click OK, to get a GUI that apparently doesn't use the Task Manager (this seems to require that Directory Services be running so as to be able to browse for the computer to shut down, or you must manually add the name of the remote computer to be shut down).
8. Click Start, Run, type "shutdown -r -t xx" (without the quotes) [xx=how many xx seconds to execute this command], click OK (I've not tried this myself).
9: Click on a blank area of the desktop or taskbar, press Alt-F4, and the standard Stand By, Turn Off, Restart dialog appears.
Tuesday, April 5, 2011
Sunday, April 3, 2011
How to find out in C# if it's 64 bit or 32 bit machine
public static class Wow
{
public static bool Is64BitProcess
{
get { return IntPtr.Size == 8; }
}
public static bool Is64BitOperatingSystem
{
get
{
// Clearly if this is a 64-bit process we must be on a 64-bit OS.
if (Is64BitProcess)
return true;
// Ok, so we are a 32-bit process, but is the OS 64-bit?
// If we are running under Wow64 than the OS is 64-bit.
bool isWow64;
return ModuleContainsFunction("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out isWow64) && isWow64;
}
}
static bool ModuleContainsFunction(string moduleName, string methodName)
{
IntPtr hModule = GetModuleHandle(moduleName);
if (hModule != IntPtr.Zero)
return GetProcAddress(hModule, methodName) != IntPtr.Zero;
return false;
}
[DllImport("kernel32.dll", SetLastError=true)]
[return:MarshalAs(UnmanagedType.Bool)]
extern static bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool isWow64);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)]
extern static IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError=true)]
extern static IntPtr GetProcAddress(IntPtr hModule, string methodName);
}
With the arrival of .Net 4, we now have two new methods (click for details):
Environment.Is64BitOperatingSystem()
Environment.Is64BitProcess()
{
public static bool Is64BitProcess
{
get { return IntPtr.Size == 8; }
}
public static bool Is64BitOperatingSystem
{
get
{
// Clearly if this is a 64-bit process we must be on a 64-bit OS.
if (Is64BitProcess)
return true;
// Ok, so we are a 32-bit process, but is the OS 64-bit?
// If we are running under Wow64 than the OS is 64-bit.
bool isWow64;
return ModuleContainsFunction("kernel32.dll", "IsWow64Process") && IsWow64Process(GetCurrentProcess(), out isWow64) && isWow64;
}
}
static bool ModuleContainsFunction(string moduleName, string methodName)
{
IntPtr hModule = GetModuleHandle(moduleName);
if (hModule != IntPtr.Zero)
return GetProcAddress(hModule, methodName) != IntPtr.Zero;
return false;
}
[DllImport("kernel32.dll", SetLastError=true)]
[return:MarshalAs(UnmanagedType.Bool)]
extern static bool IsWow64Process(IntPtr hProcess, [MarshalAs(UnmanagedType.Bool)] out bool isWow64);
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError=true)]
extern static IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
extern static IntPtr GetModuleHandle(string moduleName);
[DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError=true)]
extern static IntPtr GetProcAddress(IntPtr hModule, string methodName);
}
With the arrival of .Net 4, we now have two new methods (click for details):
Environment.Is64BitOperatingSystem()
Environment.Is64BitProcess()
Friday, April 1, 2011
Interview questions
1)What is Multi-tasking ?
Its a feature of modern operating systems with which we can run multiple programs at same time example Word,Excel etc.
(2)What is Multi-threading ?
Multi-threading forms subset of Multi-tasking instead of having to switch between programs this feature switches between different parts of the same program.Example you are writing in word and at the same time word is doing a spell check in background.
(3)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.
(4)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a free-threading model, which allows multiple threads to run against the same set of data.
(5)Can we have multiple threads in one App domain ?
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process.Each AppDomain is started with a single thread, but can create additional threads from any of its threads. Note :- All threading classes are defined in System.Threading namespace.
(6)Which namespace has threading ?
Systems.Threading has all the classes related to implement threading.Any .NET application who wants to implement threading has to import this namespace. Note :- .NET program always has atleast two threads running one the main program and second the garbage collector.
(7)How can we change priority and what the levels of priority are provided by .NET ?
Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest.In the sample provided look out for code where the second thread is ran with a high priority.
Following are different levels of Priority provided by .NET :-
v ThreadPriority.Highest
v ThreadPriority.AboveNormal
v ThreadPriority.Normal
v ThreadPriority.BelowNormal
v ThreadPriority.Lowest
(8)What does Addressof operator do in background ?
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread
(9)How can you reference current thread of the method ?
"Thread.CurrentThread" refers to the current thread running in the method."CurrentThread" is a public static property.
(10) What's Thread.Sleep() in threading ?
Thread's execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000).
(11)How can we make a thread sleep for infinite period ?
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite).To interrupt this sleep you can call the Thread.Interrupt method.
(12) What is Suspend and Resume in Threading ?
It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state. Note :- In threading interviews most people get confused with Sleep and Suspend.They look very similar.
(13)What the way to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.
(14)What's Thread.Join() in threading ?
There are two versions of Thread.Join :-
v Thread.join().
v Thread.join(Integer) this returns a boolean value.
The Thread.Join method is useful for determining if a thread has completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns True; otherwise it returns False.Once you call Join the calling procedure stops and waits for the thread to signal that it is done. Example you have "Thread1" and "Thread2" and while executing 'Thread1" you call "Thread2.Join()".So "Thread1" will wait until "Thread2" has completed its execution and the again invoke "Thread1". Thread.Join(Integer) ensures that threads do not wait for a long time.If it exceeds a specific time which is provided in integer the waiting thread will start.
(15)What are Daemon thread's and how can a thread be created as Daemon?
Daemon thread's run in background and stop automatically when nothing is running program.Example of a Daemon thread is "Garbage collector".Garbage collector runs until some .NET code is running or else its idle. You can make a thread Daemon by Thread.Isbackground=true
(16) When working with shared data in threading how do you implement synchronization ?
There are a somethings you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you'll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if two threads lock the same variable at the same time, you'll have a deadlock problem. SyncLock x 'Do something with x End SyncLock
(17)Can we use events with threading ?
Yes you can use events with threads , this is one of the technique to synchronize one thread with other.
(18)How can we know a state of a thread?
"ThreadState" property can be used to get detail of a thread.Thread can have one or combination of status.System.Threading.Threadstate enumeration has all the values to detect a state of thread.Some sample states are Isrunning,IsAlive,suspended etc.
(19) What is use of Interlocked class ?
Interlocked class provides methods by which you can achieve following functionalities :-
v increment Values.
v Decrement values.
v Exchange values between variables.
v Compare values from any thread. in a synchronization mode.
Example :- System.Threading.Interlocked.Increment(IntA)
(20) what is a monitor object?
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor object.
(21) what are wait handles ?
Twist :- What is a mutex object ? Wait handles sends signals of a thread status from one thread to other thread.There are three kind of wait modes :-
v WaitOne.
v WaitAny.
v WaitAll.
When a thread wants to release a Wait handle it can call Set method.You can use Mutex (mutually exclusive) objects to avail for the following modes.Mutex objects are synchronization objects that can only be owned by a single thread at a time.Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource. The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to signaled and the next waiting thread gets ownership
(22) what is ManualResetEvent and AutoResetEvent ?
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to nonsignaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.
(23) What is ReaderWriter Locks ?
You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows nonexclusive access when reading the resource. ReaderWriter locks are a useful alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.
(24) How can you avoid deadlock in threading ?
A good and careful planning can avoid deadlocks.There so many ways microsoft has provided by which you can reduce deadlocks example Monitor ,Interlocked classes , Wait handles, Event raising from one thread to other thread , ThreadState property which you can poll and act accordingly etc.
(25) What’s difference between thread and process?
A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context. Note:- Its difficult to cover threading interview question in this small chapter.These questions can take only to a basic level.If you are attending interviews where people are looking for threading specialist , try to get more deep in to synchronization issues as that's the important point they will stress.
Its a feature of modern operating systems with which we can run multiple programs at same time example Word,Excel etc.
(2)What is Multi-threading ?
Multi-threading forms subset of Multi-tasking instead of having to switch between programs this feature switches between different parts of the same program.Example you are writing in word and at the same time word is doing a spell check in background.
(3)What is a Thread ?
A thread is the basic unit to which the operating system allocates processor time.
(4)Did VB6 support multi-threading ?
While VB6 supports multiple single-threaded apartments, it does not support a free-threading model, which allows multiple threads to run against the same set of data.
(5)Can we have multiple threads in one App domain ?
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process.Each AppDomain is started with a single thread, but can create additional threads from any of its threads. Note :- All threading classes are defined in System.Threading namespace.
(6)Which namespace has threading ?
Systems.Threading has all the classes related to implement threading.Any .NET application who wants to implement threading has to import this namespace. Note :- .NET program always has atleast two threads running one the main program and second the garbage collector.
(7)How can we change priority and what the levels of priority are provided by .NET ?
Thread Priority can be changed by using Threadname.Priority = ThreadPriority.Highest.In the sample provided look out for code where the second thread is ran with a high priority.
Following are different levels of Priority provided by .NET :-
v ThreadPriority.Highest
v ThreadPriority.AboveNormal
v ThreadPriority.Normal
v ThreadPriority.BelowNormal
v ThreadPriority.Lowest
(8)What does Addressof operator do in background ?
The AddressOf operator creates a delegate object to the BackgroundProcess method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the Start() method of the thread
(9)How can you reference current thread of the method ?
"Thread.CurrentThread" refers to the current thread running in the method."CurrentThread" is a public static property.
(10) What's Thread.Sleep() in threading ?
Thread's execution can be paused by calling the Thread.Sleep method. This method takes an integer value that determines how long the thread should sleep. Example Thread.CurrentThread.Sleep(2000).
(11)How can we make a thread sleep for infinite period ?
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread.Sleep (System.Threading.Timeout.Infinite).To interrupt this sleep you can call the Thread.Interrupt method.
(12) What is Suspend and Resume in Threading ?
It is Similar to Sleep and Interrupt. Suspend allows you to block a thread until another thread calls Thread.Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the .NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state. Note :- In threading interviews most people get confused with Sleep and Suspend.They look very similar.
(13)What the way to stop a long running thread ?
Thread.Abort() stops the thread execution at that moment itself.
(14)What's Thread.Join() in threading ?
There are two versions of Thread.Join :-
v Thread.join().
v Thread.join(Integer) this returns a boolean value.
The Thread.Join method is useful for determining if a thread has completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns True; otherwise it returns False.Once you call Join the calling procedure stops and waits for the thread to signal that it is done. Example you have "Thread1" and "Thread2" and while executing 'Thread1" you call "Thread2.Join()".So "Thread1" will wait until "Thread2" has completed its execution and the again invoke "Thread1". Thread.Join(Integer) ensures that threads do not wait for a long time.If it exceeds a specific time which is provided in integer the waiting thread will start.
(15)What are Daemon thread's and how can a thread be created as Daemon?
Daemon thread's run in background and stop automatically when nothing is running program.Example of a Daemon thread is "Garbage collector".Garbage collector runs until some .NET code is running or else its idle. You can make a thread Daemon by Thread.Isbackground=true
(16) When working with shared data in threading how do you implement synchronization ?
There are a somethings you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you'll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if two threads lock the same variable at the same time, you'll have a deadlock problem. SyncLock x 'Do something with x End SyncLock
(17)Can we use events with threading ?
Yes you can use events with threads , this is one of the technique to synchronize one thread with other.
(18)How can we know a state of a thread?
"ThreadState" property can be used to get detail of a thread.Thread can have one or combination of status.System.Threading.Threadstate enumeration has all the values to detect a state of thread.Some sample states are Isrunning,IsAlive,suspended etc.
(19) What is use of Interlocked class ?
Interlocked class provides methods by which you can achieve following functionalities :-
v increment Values.
v Decrement values.
v Exchange values between variables.
v Compare values from any thread. in a synchronization mode.
Example :- System.Threading.Interlocked.Increment(IntA)
(20) what is a monitor object?
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor object.
(21) what are wait handles ?
Twist :- What is a mutex object ? Wait handles sends signals of a thread status from one thread to other thread.There are three kind of wait modes :-
v WaitOne.
v WaitAny.
v WaitAll.
When a thread wants to release a Wait handle it can call Set method.You can use Mutex (mutually exclusive) objects to avail for the following modes.Mutex objects are synchronization objects that can only be owned by a single thread at a time.Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource. The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to signaled and the next waiting thread gets ownership
(22) what is ManualResetEvent and AutoResetEvent ?
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to nonsignaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signaled using Set, but they automatically return to nonsignaled as soon as a waiting thread is notified that the event became signaled.
(23) What is ReaderWriter Locks ?
You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows nonexclusive access when reading the resource. ReaderWriter locks are a useful alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.
(24) How can you avoid deadlock in threading ?
A good and careful planning can avoid deadlocks.There so many ways microsoft has provided by which you can reduce deadlocks example Monitor ,Interlocked classes , Wait handles, Event raising from one thread to other thread , ThreadState property which you can poll and act accordingly etc.
(25) What’s difference between thread and process?
A thread is a path of execution that run on CPU, a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always run in a process context. Note:- Its difficult to cover threading interview question in this small chapter.These questions can take only to a basic level.If you are attending interviews where people are looking for threading specialist , try to get more deep in to synchronization issues as that's the important point they will stress.
Subscribe to:
Posts (Atom)