Thursday, July 7, 2016

Optimize code using Threading


Threading is quite helpful to optimize the performance of programming  

Parallel code execution
Processor given sometimes to execute one function and then other function parallel
  • Thread.Sleep 
    • synchronous
    • when want to block the current thread 
    • this help to run as individual thread

  • Task.Delay
    • asynchronous
    • when want only to delay the current thread without blocking
    • this help to run multiple thread at once


Sample code:




  • Foreground thread
    • thread will keep on running even though the main application is quit 
  • Background thread
    •  all the thread die if the main application quit

//Reference
using System.Threading;
using System.Threading.Task;

//Create thread
Thread obj1 = new Thread(Function1);
Thread obj2 = new Thread(Function2);

//Specially for background thread 
obj1.IsBackground = true;

//Invoke thread
obj1.Start();

static void Function1()
{
//do something 
//Wait 4 seconds
Thread.Sleep(4000);

}


References:

B' happiiiiiii always..............!

No comments:

Post a Comment