Threading enables your Visual Basic or C# program to perform concurrent processing so that you can do more than one operation at a time. For example, you can use threading to monitor input from the user, perform background tasks, and handle simultaneous streams of input.
Threads have the following properties:
- Threads enable your program to perform concurrent processing.
- The .NET Framework System.Threading namespace makes using threads easier.
- Threads share the application's resources. For more information, see Using Threads and Threading.
By default, a Visual Basic or C# program has one thread. However, auxiliary threads can be created and used to execute code in parallel with the primary thread. These threads are often called worker threads.
Example :
namespace ConsoleApplication1
{
public class ServerClass
{
// The method that will be called when the thread is started.
public void InstanceMethod()
{
Console.WriteLine(
"ServerClass.InstanceMethod is running on another thread." + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
int x =0;
for (int i = 0; i < 1000000000; i++)
{
x += x;
}
// Pause for a moment to provide a delay to make
// threads more apparent.
//Thread.Sleep(3000);
//Thread.CurrentThread.Abort();
Console.WriteLine(
"The instance method called by the worker thread has ended. " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
}
}
public class Simple
{
public static void Main()
{
Console.WriteLine("Thread Simple Sample");
DateTime datetime = System.DateTime.Now;
long elapsedTicks = System.DateTime.Now.Ticks - datetime.Ticks;
Console.WriteLine(elapsedTicks.ToString());
for (int i = 0; i < 2; i++)
{
ServerClass serverObject = new ServerClass();
Thread InstanceCaller = new Thread(
new ThreadStart(serverObject.InstanceMethod));
// Start the thread.
InstanceCaller.Start();
Console.WriteLine("The Main() thread calls this after "
+ "starting the new InstanceCaller thread.");
}
elapsedTicks = System.DateTime.Now.Ticks - datetime.Ticks;
Console.WriteLine(elapsedTicks.ToString());
Console.ReadLine();
}
}
}
A thread pool is a collection of threads that can be used to perform several tasks in the background. This leaves the primary thread free to perform other tasks asynchronously.
System.Threading.ThreadPool.QueueUserWorkItem(
new System.Threading.WaitCallback(AnotherLongTask));ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
No comments:
Post a Comment