SlideShare a Scribd company logo
1 of 50
Mul$threaded	
  and	
  Async	
  
Programming	
  in	
  C#	
  +	
  File	
  IO	
  
              Jussi	
  Pohjolainen	
  
  Tampere	
  University	
  of	
  Applied	
  Sciences	
  
Delegates	
  
•  You	
  can	
  invoke	
  a	
  method	
  (determined	
  by	
  
   run$me)	
  from	
  a	
  delegate	
  
    public delegate int SomeMethod(int x, int y);

    Console.WriteLine("Thread is " +
    Thread.CurrentThread.ManagedThreadId);

    SomeMethod a = new SomeMethod(Sum);

    Console.WriteLine( a.Invoke(5,5) );
•  It's	
  possible	
  to	
  make	
  the	
  invoke	
  in	
  separate	
  thread!
Asynchronous	
  Delegate	
  
•  By	
  using	
  the	
  same	
  delegate,	
  but	
  calling	
  
   BeginInvoke,	
  the	
  method	
  is	
  done	
  in	
  separate	
  
   thread	
  
    –  public IAsyncResult BeginInvoke(parameters..,
       AsyncCallback cb, object state)
    –  public returnType EndInvoke(IAsyncResult result)

•  If	
  the	
  method	
  returns	
  something,	
  use	
  
   EndInvoke	
  to	
  get	
  the	
  return	
  value.
using System;
using System.Threading;
public delegate int SomeMethod(int x, int y);
class MyMain
{
     public static void Main()
     {
          SomeMethod a = new SomeMethod(Sum);
         Console.WriteLine("Firing Asynchronous method");
         // IAsyncResult - Represents the status of an asynchronous operation.
         IAsyncResult iftAR = a.BeginInvoke(5, 5, null, null);
         Console.WriteLine("Doing some work here!");
         int answer = a.EndInvoke(iftAR);
         Console.WriteLine(answer);
    }
    public static int Sum(int x, int y)
    {
         Console.WriteLine("Thread is " + Thread.CurrentThread.ManagedThreadId);
         Thread.Sleep(2000);
         return x + y;
    }
}
Synchronizing	
  Calling	
  Thread	
  
•  If	
  we	
  look	
  at	
  this	
  more	
  closely	
  
    –    Console.WriteLine("Firing Asynchronous method");
    –    IAsyncResult iftAR = a.BeginInvoke(5, 5, null, null);
    –    Console.WriteLine("Doing some work here!");
    –    // We are waiting here!
    –    int answer = a.EndInvoke(iftAR);
•  We	
  realize	
  that	
  the	
  a.EndInvoke	
  waits	
  un$l	
  the	
  
   "calcula$on"	
  is	
  done
using System;
using System.Threading;

public delegate int SomeMethod(int x, int y);

class MyMain
{
      public static void Main()
      {
            SomeMethod a = new SomeMethod(Sum);

           Console.WriteLine("Firing Asynchronous method");
           IAsyncResult iftAR = a.BeginInvoke(5, 5, null, null);

           while(!iftAR.IsCompleted)
           {
                 Console.WriteLine("Doing some work here!");
           }

           int answer = a.EndInvoke(iftAR);
           Console.WriteLine(answer);
     }

     public static int Sum(int x, int y)
     {
           Console.WriteLine("Thread is " + Thread.CurrentThread.ManagedThreadId);
           Thread.Sleep(2000);
           return x + y;
     }
}
Rid	
  of	
  Polling	
  
•  Instead	
  of	
  polling,	
  it	
  would	
  be	
  a	
  good	
  idea	
  to	
  
   have	
  a	
  secondary	
  thread	
  to	
  inform	
  the	
  calling	
  
   thread	
  when	
  the	
  task	
  is	
  finished.	
  
using System;
using System.Threading;

public delegate int SomeMethod(int x, int y);

class MyMain
{
       private static bool done = false;

      public static void Main()
      {
             SomeMethod a = new SomeMethod(Sum);

             Console.WriteLine("Firing Asynchronous method");
             IAsyncResult iftAR = a.BeginInvoke(5, 5, new AsyncCallback(Done), null);

             while(!done)
             {
                    Console.WriteLine("Doing some work here!");
             }

             int answer = a.EndInvoke(iftAR);
             Console.WriteLine(answer);
      }

      public static int Sum(int x, int y)
      {
             Console.WriteLine("Thread is " + Thread.CurrentThread.ManagedThreadId);
             Thread.Sleep(2000);
             return x + y;
      }

      public static void Done(IAsyncResult result)
      {
             done = true;
      }
}
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;

public delegate int SomeMethod(int x, int y);

class MyMain
{
       private static bool done = false;
       public static void Main()
       {
              SomeMethod a = new SomeMethod(Sum);
              Console.WriteLine("Firing Asynchronous method");
             // Passing custom state data
              a.BeginInvoke(5, 5, new AsyncCallback(Done), "Message Sending!");
              while(!done)
              {
                     Console.WriteLine("Doing some work here!");
              }
       }
       public static void Done(IAsyncResult iftAR)
       {
              // IAsyncResult is interface, actual object is AsyncResult
              AsyncResult ar = (AsyncResult) iftAR;

             // AsyncResult holds the delegate
             SomeMethod sm = (SomeMethod) ar.AsyncDelegate;

             // Make the call
             int answer = sm.EndInvoke(iftAR);
             Console.WriteLine(answer);

             // Also print the message!
             string msg = (string) iftAR.AsyncState;
             Console.WriteLine(msg);

             done = true;
      }
}
THREADING	
  NAMESPACE	
  
Threading	
  Namespace	
  
•  Threading	
  namespace	
  provides	
  lot	
  of	
  classes	
  
   for	
  crea$ng	
  threads	
  
   –  Thread	
  –	
  Main	
  class	
  for	
  crea$ng	
  a	
  thread	
  
   –  ThreadStart	
  –	
  delegate	
  used	
  to	
  specify	
  which	
  
      method	
  is	
  run	
  under	
  a	
  thread	
  
   –  Timer	
  –	
  Mechanism	
  for	
  execu$ng	
  a	
  method	
  at	
  
      specified	
  intervals	
  
   –  Lot	
  of	
  locking	
  mechanisms	
  	
  
System.Threading.Thread	
  Class	
  
•  Some	
  sta$c	
  members	
  
    –  CurrentThread	
  –	
  get	
  the	
  current	
  thread	
  
    –  Sleep()	
  –	
  Suspend	
  current	
  thread	
  
•  Some	
  AZributes	
  
    –  IsAlive	
  
    –  Name	
  
    –  Priority	
  
•  	
  Some	
  Methods	
  
    –    Abort()	
  
    –    Join()	
  
    –    Start()	
  
    –    …	
  
Ge]ng	
  Informa$on	
  About	
  the	
  Current	
  
                    Thread	
  
using System;
using System.Threading;

class MyMain
{
     public static void Main()
     {
          Thread.CurrentThread.Name = "My THREAD!";

          Console.WriteLine("Name: ");
          Console.WriteLine(Thread.CurrentThread.Name);
          Console.WriteLine("IsAlive: ");
          Console.WriteLine(Thread.CurrentThread.IsAlive);
          Console.WriteLine("Priority: ");
          Console.WriteLine(Thread.CurrentThread.Priority);
          Console.WriteLine("ThreadState: ");
          Console.WriteLine(Thread.CurrentThread.ThreadState);
     }
}
using System;
using System.Threading;

public class Simple
{
   public static void DoThis()
   {
      int i=0;
      while (true)
      {
         Console.WriteLine("Running in its own thread. " + i);
         Thread.Sleep(500);
         i++;
      }
   }

    public static void Main()
    {
       Thread aThread = new Thread(new ThreadStart(DoThis));
       aThread.Start();
       Thread bThread = new Thread(new ThreadStart(DoThis));
       bThread.Start();
    }
}
using System;
using System.Threading;

public class Simple
{
   public static void DoThis(object data)
   {
      int i=0;
      while (i < (int) data)
      {
         Console.WriteLine("Running in its own thread. " + i);
         Thread.Sleep(500);
         i++;
      }
   }

    public static void Main()
    {
       Thread aThread = new Thread(new ParameterizedThreadStart(DoThis));
       aThread.Start(10);
    }
}
About	
  Locking	
  
•  When	
  mul$ple	
  threads	
  access	
  same	
  
   informa$on	
  -­‐>	
  unstable	
  data	
  
•  Example:	
  one	
  bank	
  account,	
  two	
  withdrawals	
  
   at	
  the	
  same	
  $me	
  
    –  1)	
  is	
  there	
  enough	
  money?	
  
    –  2)	
  if	
  true,	
  withdraw	
  
•  We	
  have	
  a	
  problem	
  if	
  these	
  steps	
  are	
  done	
  at	
  
   the	
  same	
  $me:	
  1,1,2,2	
  
Solu$on	
  
•    One	
  solu$on	
  is	
  to	
  use	
  lock	
  keyword	
  
•    If	
  on	
  thread	
  holds	
  a	
  lock,	
  others	
  wait	
  
•    lock	
  is	
  any	
  object	
  
•    Usage	
  lock(object){	
  	
  }	
  
Timers	
  
using System;
using System.Threading;

class Hello
{
      public static void DoThis(object data)
      {
            Console.WriteLine("Hello!");
      }

     public static void Main()
     {
           TimerCallback timeCB = new TimerCallback(DoThis);
           Timer t = new Timer(timeCB,   // call back delegate object
                                   null,   // Any info to the method
                                   0,      // Time before first invocation
                                   1000); // Interval

           Console.ReadLine();
     }
}
Background	
  Worker	
  
•  hZp://msdn.microsog.com/en-­‐us/library/cc221403(v=vs.95).aspx	
  
   private void Button_Click_2(object sender, RoutedEventArgs e)
      {
          BackgroundWorker bw = new BackgroundWorker();
          bw.DoWork += DoTheWork;
          bw.RunWorkerCompleted += Complete;
          bw.RunWorkerAsync();

      }

      public void DoTheWork(object sender, DoWorkEventArgs e)
      {
          Thread.Sleep(500);
      }

      public void Complete(object sender, RunWorkerCompletedEventArgs e)
      {
          Title = "Hello";
      }
GUI	
  AND	
  THREADING	
  
Access	
  UI	
  from	
  Thread	
  
•  If	
  a	
  secondary	
  thread	
  aZempt	
  to	
  access	
  a	
  control	
  it	
  did	
  not	
  
     create	
  =>	
  run$me	
  error!	
  
	
  
 private void Button_Click_2(object sender, RoutedEventArgs e)
 {
     Thread thread = new Thread(new ThreadStart(ModifyTitle));
     thread.Start();
}

// Runtime Exception!
public void ModifyTitle()
{
    Title = "Hello World";
}
Dispatcher	
  Class	
  
•  Dispatcher	
  class	
  allows	
  you	
  to	
  modify	
  UI	
  from	
  
   secondary	
  thread	
  
•  Read	
  
    –  hZp://msdn.microsog.com/en-­‐us/magazine/
       cc163328.aspx	
  
private void Button_Click_2(object sender, RoutedEventArgs e)
{
    Thread t = new Thread(new ThreadStart(ModifyTitle));
    t.Start();
}

public void ModifyTitle()
{
    Thread.Sleep(1000);

    // Change title to "Hello"
    Dispatcher.Invoke(new Action(ChangeTitle));

    Thread.Sleep(1000);

    // Lambda
    Dispatcher.Invoke(() => this.Title = "World");

    Thread.Sleep(1000);

    Dispatcher.Invoke(() => this.Title = "");

    string newTitle = "Hello World!";

    for (int i = 0; i < newTitle.Length; i++)
    {
        Thread.Sleep(100);
        Dispatcher.Invoke(() => this.Title += newTitle[i]);
    }
}

public void ChangeTitle()
{
    this.Title = "Hello";
}
Upda$ng	
  UI	
  and	
  Timer	
  
•  Timer	
  calls	
  certain	
  method	
  in	
  interval	
  
•  When	
  using	
  Threading.Timer	
  the	
  task	
  is	
  in	
  
   different	
  thread	
  
       –  Use	
  Dispatcher.Invoke	
  to	
  manipulate	
  the	
  UI	
  thread	
  
•  When	
  using	
  
   Windows.Threading.DispatcherTimer,	
  the	
  task	
  in	
  
   in	
  UI	
  thread	
  
       –  If	
  this	
  performs	
  a	
  $me	
  consuming	
  task,	
  the	
  UI	
  will	
  
          freeze	
  


	
  
ASYNC	
  CALLS	
  
Aync	
  Calls	
  Under	
  .NET	
  4.5	
  
•  Two	
  new	
  keywords	
  to	
  simplify	
  threading	
  even	
  
   more	
  
    –  async	
  and	
  await	
  
•  Compiler	
  will	
  generate	
  lot	
  of	
  code	
  when	
  using	
  
   these	
  keywords	
  
•  async	
  
    –  Method	
  should	
  be	
  called	
  in	
  an	
  asynchronous	
  manner	
  
       automa$cally	
  
•  await	
  
    –  Pause	
  current	
  thread	
  un$l	
  task	
  is	
  complete	
  
async	
  and	
  await	
  
•  In	
  .NET	
  4.5,	
  new	
  keywords:	
  async	
  and	
  await	
  
•  Simplifies	
  threading,	
  generates	
  a	
  lot	
  of	
  code!	
  
•  See:	
  
    –  hZp://blogs.msdn.com/b/pfxteam/archive/
       2012/04/12/10293335.aspx	
  
namespace WpfApplication2
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            WebClient wb = new WebClient();
            Task<string> result = wb.DownloadStringTaskAsync(new Uri("http://www.tamk.fi/"));

            string r = await result;

            Contents.Text = r;
        }
    }
}
FILE	
  I/O	
  
Overview	
  
•  System.IO	
  namespace	
  provides	
  number	
  of	
  classes	
  
   for	
  reading	
  and	
  wri$ng	
  
•  Store	
  and	
  retrieve	
  primi$ve	
  types	
  
    –  BinaryReader,	
  BinaryWriter	
  
•  Store	
  and	
  retrieve	
  text	
  
    –  StreamReader,	
  StreamWriter	
  
•  Buffered	
  reading	
  
    –  BufferedStream	
  
•  Helper	
  classes	
  like	
  File	
  (sta$c),	
  FileInfo	
  (object	
  
   reference	
  
Reading	
  and	
  Wri$ng	
  Text	
  
•  StreamWriter	
  and	
  StreamReader	
  use	
  useful	
  
   when	
  need	
  for	
  read	
  or	
  write	
  text	
  
•  By	
  default:	
  Unicode	
  
   –  Can	
  be	
  changed:	
  pass	
  System.TextEncoding	
  object	
  
      reference	
  
•  Methods	
  
   –  Write(),	
  WriteLine()	
  
Wri$ng	
  
class SaveText
{
    public static void Main()
    {
        StreamWriter writer = File.CreateText("./textfile.txt");
        // Nothing happens! Why?
        writer.WriteLine("Hello World!");
        writer.WriteLine("Hello World!");
    }
}
Wri$ng:	
  Flush	
  it!	
  
using System;
using System.IO;

class SaveText
{
    public static void Main()
    {
        StreamWriter writer = File.CreateText("./textfile.txt");

        writer.WriteLine("Hello World!");
        writer.WriteLine("Hello World!");
        writer.Flush();
    }
}
Wri$ng:	
  Stream	
  should	
  be	
  closed!	
  
using System;
using System.IO;

class SaveText
{
    public static void Main()
    {
        StreamWriter writer = File.CreateText("./textfile.txt");

         writer.WriteLine("Hello World!");
         writer.WriteLine("Hello World!");
         writer.Flush();
         writer.Close();
     }
}
Wri$ng:	
  Flushing	
  is	
  done	
  when	
  
                      closing!	
  
using System;
using System.IO;

class SaveText
{
    public static void Main()
    {
        StreamWriter writer = File.CreateText("./textfile.txt");

        writer.WriteLine("Hello World!");
        writer.WriteLine("Hello World!");
        writer.Close();
    }
}
Wri$ng:	
  using	
  
using System;
using System.IO;

class ReadText
{
     public static void Main()
     {
          using( StreamWriter writer = File.CreateText("./textfile.txt") )
          {
               writer.WriteLine("Hello World!");
               writer.WriteLine("Hello World!");
          }
     }
}
Reading	
  Text	
  
using System;
using System.IO;

class ReadText
{
     public static void Main()
     {
          using( StreamReader reader = File.OpenText("./textfile.txt") )
          {
               string input = null;
               while((input = reader.ReadLine()) != null)
               {
                    Console.WriteLine(input);
               }
          }
     }
}
Reading	
  and	
  Wri$ng	
  Binary	
  
using System;
using System.IO;

class ReadBinary
{
     public static void Main()
     {
          using( BinaryWriter writer = new BinaryWriter( File.OpenWrite("./test.dat") ) )
          {
               writer.Write(2.2);
          }

          using( BinaryReader reader = new BinaryReader( File.OpenRead("./test.dat") ) )
          {
               Console.WriteLine(reader.ReadDouble());
          }
     }
}
Watching	
  Files	
  
•  Monitor	
  or	
  watch	
  files	
  using	
  
   FileSystemWatcher	
  class	
  
•  Really	
  easy	
  to	
  implement	
  
    –  Which	
  folder	
  are	
  we	
  looking?	
  
    –  Set	
  up	
  things	
  to	
  listen	
  
    –  Add	
  Filters	
  
    –  Add	
  Event	
  Handlers	
  
    –  Start	
  listening	
  
Example	
  
using System;
using System.IO;

class Watcher
{
      public static void Main()
      {
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = "/Users/pohjus/Desktop/tuhoa/";
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;

           watcher.Filter = "*.txt";

           watcher.Changed += (object source, FileSystemEventArgs e) => Console.Write("Changed");
           watcher.Deleted += (object source, FileSystemEventArgs e) => Console.Write("Deleted");

           watcher.EnableRaisingEvents = true;

           Console.Read();
     }
}
Serializable	
  
•  Serializa$on?	
  Store	
  an	
  state	
  of	
  the	
  object	
  into	
  
   stream!	
  
•  Example:	
  Store	
  app	
  preferences	
  into	
  a	
  file.	
  
   Preference	
  informa$on	
  are	
  stored	
  in	
  object.	
  
•  How?	
  Mark	
  a	
  class	
  as	
  Serializable	
  and	
  use	
  
   classes	
  to	
  store	
  and	
  open	
  the	
  object	
  
•  You	
  can	
  save	
  the	
  object	
  as	
  binary	
  or	
  xml	
  (use	
  
   XMLSerializer	
  -­‐	
  class)	
  
using	
  System;	
  
using	
  System.IO;	
  
using	
  System.Run$me.Serializa$on.FormaZers.Binary;	
  
	
  
[Serializable]	
  
class	
  Person	
  
{	
  
         	
  public	
  string	
  Name	
  {	
  get;	
  set;	
  }	
  
         	
  public	
  int	
  Age	
  {	
  get;	
  set;	
  }	
  
}	
  
class	
  SerializableExample	
  
{	
  
         	
  public	
  sta$c	
  void	
  Main()	
  
         	
  {	
  
         	
        	
  Person	
  jack	
  =	
  new	
  Person()	
  {	
  Name	
  =	
  "Jack",	
  Age	
  =	
  20	
  };	
  
	
  
         	
        	
  //	
  Let's	
  save	
  jack	
  as	
  binary	
  
         	
        	
  BinaryFormaZer	
  binFormat	
  =	
  new	
  BinaryFormaZer();	
  
	
  
         	
        	
  //	
  And	
  in	
  which	
  file?	
  
         	
        	
  using(FileStream	
  fs	
  =	
  new	
  FileStream("person.dat",	
  FileMode.Create))	
  
         	
        	
  {	
  
         	
        	
           	
  //	
  Let's	
  do	
  it!	
  
         	
        	
           	
  binFormat.Serialize(fs,	
  jack);	
  
         	
        	
  }	
  
         	
  }	
  
}	
  
	
  
using	
  System;	
  
using	
  System.IO;	
  
using	
  System.Run$me.Serializa$on.FormaZers.Binary;	
  
	
  
[Serializable]	
  
class	
  Person	
  
{	
  
         	
  public	
  string	
  Name	
  {	
  get;	
  set;	
  }	
  
         	
  public	
  int	
  Age	
  {	
  get;	
  set;	
  }	
  
}	
  
	
  
class	
  SerializableExample	
  
{	
  
         	
  public	
  sta$c	
  void	
  Main()	
  
         	
  {	
  
         	
        	
  BinaryFormaZer	
  binFormat	
  =	
  new	
  BinaryFormaZer();	
  
	
  
         	
        	
  //	
  Deserialize!	
  
         	
        	
  using(FileStream	
  fs	
  =	
  new	
  FileStream("person.dat",	
  FileMode.Open))	
  
         	
        	
  {	
  
         	
        	
           	
  Person	
  jack2	
  =	
  (Person)	
  binFormat.Deserialize(fs);	
  
         	
        	
           	
  Console.WriteLine(jack2.Name);	
  
         	
        	
           	
  Console.WriteLine(jack2.Age);	
  
         	
        	
  }	
  
         	
  }	
  
}	
  
ABOUT	
  WIN	
  DESKTOP	
  APPS	
  
WPF	
  
•  Windows	
  Presenta$on	
  Founda$on	
  (or	
  WPF)	
  is	
  
   a	
  computer-­‐sogware	
  graphical	
  subsystem	
  for	
  
   rendering	
  user	
  interfaces	
  in	
  Windows-­‐based	
  
   applica$ons	
  
•  WPF	
  employs	
  XAML,	
  an	
  XML-­‐based	
  language,	
  
   to	
  define	
  and	
  link	
  various	
  UI	
  elements	
  
•  See	
  
   –  hZp://msdn.microsog.com/en-­‐us/library/
      ms752299.aspx	
  
C# Multithreading and Async File IO Guide
C# Multithreading and Async File IO Guide
C# Multithreading and Async File IO Guide
C# Multithreading and Async File IO Guide
C# Multithreading and Async File IO Guide

More Related Content

What's hot

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksDoug Hawkins
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011julien.ponge
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Campjulien.ponge
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...julien.ponge
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor ConcurrencyAlex Miller
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++nsm.nikhil
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded ProgrammingAdil Jafri
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Nilesh Jayanandana
 

What's hot (20)

The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java practical
Java practicalJava practical
Java practical
 
JVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's TricksJVM Mechanics: Understanding the JIT's Tricks
JVM Mechanics: Understanding the JIT's Tricks
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Parallel streams in java 8
Parallel streams in java 8Parallel streams in java 8
Parallel streams in java 8
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Java 7 at SoftShake 2011
Java 7 at SoftShake 2011Java 7 at SoftShake 2011
Java 7 at SoftShake 2011
 
Java 7 JUG Summer Camp
Java 7 JUG Summer CampJava 7 JUG Summer Camp
Java 7 JUG Summer Camp
 
DCN Practical
DCN PracticalDCN Practical
DCN Practical
 
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
Java 7 Launch Event at LyonJUG, Lyon France. Fork / Join framework and Projec...
 
Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
Actor Concurrency
Actor ConcurrencyActor Concurrency
Actor Concurrency
 
Writing native bindings to node.js in C++
Writing native bindings to node.js in C++Writing native bindings to node.js in C++
Writing native bindings to node.js in C++
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done right
 
13multithreaded Programming
13multithreaded Programming13multithreaded Programming
13multithreaded Programming
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
Comparing JVM languages
Comparing JVM languagesComparing JVM languages
Comparing JVM languages
 

Viewers also liked

R Programming: Variables & Data Types
R Programming: Variables & Data TypesR Programming: Variables & Data Types
R Programming: Variables & Data TypesRsquared Academy
 
C# Delegates, Events, Lambda
C# Delegates, Events, LambdaC# Delegates, Events, Lambda
C# Delegates, Events, LambdaJussi Pohjolainen
 
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)Ryan Cuprak
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event HandlingJussi Pohjolainen
 
Building a scalable data science platform with R
Building a scalable data science platform with RBuilding a scalable data science platform with R
Building a scalable data science platform with RRevolution Analytics
 

Viewers also liked (9)

R Programming: Variables & Data Types
R Programming: Variables & Data TypesR Programming: Variables & Data Types
R Programming: Variables & Data Types
 
Microsoft Azure + R
Microsoft Azure + RMicrosoft Azure + R
Microsoft Azure + R
 
C# Delegates, Events, Lambda
C# Delegates, Events, LambdaC# Delegates, Events, Lambda
C# Delegates, Events, Lambda
 
C# for Java Developers
C# for Java DevelopersC# for Java Developers
C# for Java Developers
 
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
 
C# Delegates and Event Handling
C# Delegates and Event HandlingC# Delegates and Event Handling
C# Delegates and Event Handling
 
Building a scalable data science platform with R
Building a scalable data science platform with RBuilding a scalable data science platform with R
Building a scalable data science platform with R
 
R and Data Science
R and Data ScienceR and Data Science
R and Data Science
 
Risk Management Framework
Risk Management FrameworkRisk Management Framework
Risk Management Framework
 

Similar to C# Multithreading and Async File IO Guide

Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...DroidConTLV
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency GotchasAlex Miller
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundKarel Zikmund
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel ZikmundKarel Zikmund
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Víctor Bolinches
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2Duong Thanh
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NETMarcin Tyborowski
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programmingSonam Sharma
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on AndroidTomáš Kypta
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 

Similar to C# Multithreading and Async File IO Guide (20)

Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
Tricks to Making a Realtime SurfaceView Actually Perform in Realtime - Maarte...
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel ZikmundNDC Sydney 2019 - Async Demystified -- Karel Zikmund
NDC Sydney 2019 - Async Demystified -- Karel Zikmund
 
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
.NET Core Summer event 2019 in Brno, CZ - Async demystified -- Karel Zikmund
 
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
Paradigma FP y OOP usando técnicas avanzadas de Programación | Programacion A...
 
CSharp for Unity Day2
CSharp for Unity Day2CSharp for Unity Day2
CSharp for Unity Day2
 
History of asynchronous in .NET
History of asynchronous in .NETHistory of asynchronous in .NET
History of asynchronous in .NET
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 
Reactive programming on Android
Reactive programming on AndroidReactive programming on Android
Reactive programming on Android
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Thread 1
Thread 1Thread 1
Thread 1
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 

More from Jussi Pohjolainen

libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferencesJussi Pohjolainen
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationJussi Pohjolainen
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDXJussi Pohjolainen
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript DevelopmentJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame AnimationJussi Pohjolainen
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDXJussi Pohjolainen
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDXJussi Pohjolainen
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesJussi Pohjolainen
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platformJussi Pohjolainen
 

More from Jussi Pohjolainen (20)

Moved to Speakerdeck
Moved to SpeakerdeckMoved to Speakerdeck
Moved to Speakerdeck
 
Java Web Services
Java Web ServicesJava Web Services
Java Web Services
 
Box2D and libGDX
Box2D and libGDXBox2D and libGDX
Box2D and libGDX
 
libGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and PreferenceslibGDX: Screens, Fonts and Preferences
libGDX: Screens, Fonts and Preferences
 
libGDX: Tiled Maps
libGDX: Tiled MapslibGDX: Tiled Maps
libGDX: Tiled Maps
 
libGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame AnimationlibGDX: User Input and Frame by Frame Animation
libGDX: User Input and Frame by Frame Animation
 
Intro to Building Android Games using libGDX
Intro to Building Android Games using libGDXIntro to Building Android Games using libGDX
Intro to Building Android Games using libGDX
 
Advanced JavaScript Development
Advanced JavaScript DevelopmentAdvanced JavaScript Development
Advanced JavaScript Development
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
libGDX: Scene2D
libGDX: Scene2DlibGDX: Scene2D
libGDX: Scene2D
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: Simple Frame Animation
libGDX: Simple Frame AnimationlibGDX: Simple Frame Animation
libGDX: Simple Frame Animation
 
libGDX: User Input
libGDX: User InputlibGDX: User Input
libGDX: User Input
 
Implementing a Simple Game using libGDX
Implementing a Simple Game using libGDXImplementing a Simple Game using libGDX
Implementing a Simple Game using libGDX
 
Building Android games using LibGDX
Building Android games using LibGDXBuilding Android games using LibGDX
Building Android games using LibGDX
 
Android Threading
Android ThreadingAndroid Threading
Android Threading
 
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and GesturesCreating Asha Games: Game Pausing, Orientation, Sensors and Gestures
Creating Asha Games: Game Pausing, Orientation, Sensors and Gestures
 
Creating Games for Asha - platform
Creating Games for Asha - platformCreating Games for Asha - platform
Creating Games for Asha - platform
 
Intro to Asha UI
Intro to Asha UIIntro to Asha UI
Intro to Asha UI
 

Recently uploaded

React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkPixlogix Infotech
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...itnewsafrica
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfAarwolf Industries LLC
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integrationmarketing932765
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Jeffrey Haguewood
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Kaya Weers
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Nikki Chapple
 

Recently uploaded (20)

React Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App FrameworkReact Native vs Ionic - The Best Mobile App Framework
React Native vs Ionic - The Best Mobile App Framework
 
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...Abdul Kader Baba- Managing Cybersecurity Risks  and Compliance Requirements i...
Abdul Kader Baba- Managing Cybersecurity Risks and Compliance Requirements i...
 
Landscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdfLandscape Catalogue 2024 Australia-1.pdf
Landscape Catalogue 2024 Australia-1.pdf
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS:  6 Ways to Automate Your Data IntegrationBridging Between CAD & GIS:  6 Ways to Automate Your Data Integration
Bridging Between CAD & GIS: 6 Ways to Automate Your Data Integration
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
Email Marketing Automation for Bonterra Impact Management (fka Social Solutio...
 
Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)Design pattern talk by Kaya Weers - 2024 (v2)
Design pattern talk by Kaya Weers - 2024 (v2)
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
Microsoft 365 Copilot: How to boost your productivity with AI – Part one: Ado...
 

C# Multithreading and Async File IO Guide

  • 1. Mul$threaded  and  Async   Programming  in  C#  +  File  IO   Jussi  Pohjolainen   Tampere  University  of  Applied  Sciences  
  • 2. Delegates   •  You  can  invoke  a  method  (determined  by   run$me)  from  a  delegate   public delegate int SomeMethod(int x, int y); Console.WriteLine("Thread is " + Thread.CurrentThread.ManagedThreadId); SomeMethod a = new SomeMethod(Sum); Console.WriteLine( a.Invoke(5,5) ); •  It's  possible  to  make  the  invoke  in  separate  thread!
  • 3. Asynchronous  Delegate   •  By  using  the  same  delegate,  but  calling   BeginInvoke,  the  method  is  done  in  separate   thread   –  public IAsyncResult BeginInvoke(parameters.., AsyncCallback cb, object state) –  public returnType EndInvoke(IAsyncResult result) •  If  the  method  returns  something,  use   EndInvoke  to  get  the  return  value.
  • 4. using System; using System.Threading; public delegate int SomeMethod(int x, int y); class MyMain { public static void Main() { SomeMethod a = new SomeMethod(Sum); Console.WriteLine("Firing Asynchronous method"); // IAsyncResult - Represents the status of an asynchronous operation. IAsyncResult iftAR = a.BeginInvoke(5, 5, null, null); Console.WriteLine("Doing some work here!"); int answer = a.EndInvoke(iftAR); Console.WriteLine(answer); } public static int Sum(int x, int y) { Console.WriteLine("Thread is " + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); return x + y; } }
  • 5. Synchronizing  Calling  Thread   •  If  we  look  at  this  more  closely   –  Console.WriteLine("Firing Asynchronous method"); –  IAsyncResult iftAR = a.BeginInvoke(5, 5, null, null); –  Console.WriteLine("Doing some work here!"); –  // We are waiting here! –  int answer = a.EndInvoke(iftAR); •  We  realize  that  the  a.EndInvoke  waits  un$l  the   "calcula$on"  is  done
  • 6. using System; using System.Threading; public delegate int SomeMethod(int x, int y); class MyMain { public static void Main() { SomeMethod a = new SomeMethod(Sum); Console.WriteLine("Firing Asynchronous method"); IAsyncResult iftAR = a.BeginInvoke(5, 5, null, null); while(!iftAR.IsCompleted) { Console.WriteLine("Doing some work here!"); } int answer = a.EndInvoke(iftAR); Console.WriteLine(answer); } public static int Sum(int x, int y) { Console.WriteLine("Thread is " + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); return x + y; } }
  • 7. Rid  of  Polling   •  Instead  of  polling,  it  would  be  a  good  idea  to   have  a  secondary  thread  to  inform  the  calling   thread  when  the  task  is  finished.  
  • 8. using System; using System.Threading; public delegate int SomeMethod(int x, int y); class MyMain { private static bool done = false; public static void Main() { SomeMethod a = new SomeMethod(Sum); Console.WriteLine("Firing Asynchronous method"); IAsyncResult iftAR = a.BeginInvoke(5, 5, new AsyncCallback(Done), null); while(!done) { Console.WriteLine("Doing some work here!"); } int answer = a.EndInvoke(iftAR); Console.WriteLine(answer); } public static int Sum(int x, int y) { Console.WriteLine("Thread is " + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(2000); return x + y; } public static void Done(IAsyncResult result) { done = true; } }
  • 9. using System; using System.Threading; using System.Runtime.Remoting.Messaging; public delegate int SomeMethod(int x, int y); class MyMain { private static bool done = false; public static void Main() { SomeMethod a = new SomeMethod(Sum); Console.WriteLine("Firing Asynchronous method"); // Passing custom state data a.BeginInvoke(5, 5, new AsyncCallback(Done), "Message Sending!"); while(!done) { Console.WriteLine("Doing some work here!"); } } public static void Done(IAsyncResult iftAR) { // IAsyncResult is interface, actual object is AsyncResult AsyncResult ar = (AsyncResult) iftAR; // AsyncResult holds the delegate SomeMethod sm = (SomeMethod) ar.AsyncDelegate; // Make the call int answer = sm.EndInvoke(iftAR); Console.WriteLine(answer); // Also print the message! string msg = (string) iftAR.AsyncState; Console.WriteLine(msg); done = true; } }
  • 11. Threading  Namespace   •  Threading  namespace  provides  lot  of  classes   for  crea$ng  threads   –  Thread  –  Main  class  for  crea$ng  a  thread   –  ThreadStart  –  delegate  used  to  specify  which   method  is  run  under  a  thread   –  Timer  –  Mechanism  for  execu$ng  a  method  at   specified  intervals   –  Lot  of  locking  mechanisms    
  • 12. System.Threading.Thread  Class   •  Some  sta$c  members   –  CurrentThread  –  get  the  current  thread   –  Sleep()  –  Suspend  current  thread   •  Some  AZributes   –  IsAlive   –  Name   –  Priority   •   Some  Methods   –  Abort()   –  Join()   –  Start()   –  …  
  • 13. Ge]ng  Informa$on  About  the  Current   Thread   using System; using System.Threading; class MyMain { public static void Main() { Thread.CurrentThread.Name = "My THREAD!"; Console.WriteLine("Name: "); Console.WriteLine(Thread.CurrentThread.Name); Console.WriteLine("IsAlive: "); Console.WriteLine(Thread.CurrentThread.IsAlive); Console.WriteLine("Priority: "); Console.WriteLine(Thread.CurrentThread.Priority); Console.WriteLine("ThreadState: "); Console.WriteLine(Thread.CurrentThread.ThreadState); } }
  • 14. using System; using System.Threading; public class Simple { public static void DoThis() { int i=0; while (true) { Console.WriteLine("Running in its own thread. " + i); Thread.Sleep(500); i++; } } public static void Main() { Thread aThread = new Thread(new ThreadStart(DoThis)); aThread.Start(); Thread bThread = new Thread(new ThreadStart(DoThis)); bThread.Start(); } }
  • 15. using System; using System.Threading; public class Simple { public static void DoThis(object data) { int i=0; while (i < (int) data) { Console.WriteLine("Running in its own thread. " + i); Thread.Sleep(500); i++; } } public static void Main() { Thread aThread = new Thread(new ParameterizedThreadStart(DoThis)); aThread.Start(10); } }
  • 16. About  Locking   •  When  mul$ple  threads  access  same   informa$on  -­‐>  unstable  data   •  Example:  one  bank  account,  two  withdrawals   at  the  same  $me   –  1)  is  there  enough  money?   –  2)  if  true,  withdraw   •  We  have  a  problem  if  these  steps  are  done  at   the  same  $me:  1,1,2,2  
  • 17. Solu$on   •  One  solu$on  is  to  use  lock  keyword   •  If  on  thread  holds  a  lock,  others  wait   •  lock  is  any  object   •  Usage  lock(object){    }  
  • 18. Timers   using System; using System.Threading; class Hello { public static void DoThis(object data) { Console.WriteLine("Hello!"); } public static void Main() { TimerCallback timeCB = new TimerCallback(DoThis); Timer t = new Timer(timeCB, // call back delegate object null, // Any info to the method 0, // Time before first invocation 1000); // Interval Console.ReadLine(); } }
  • 19. Background  Worker   •  hZp://msdn.microsog.com/en-­‐us/library/cc221403(v=vs.95).aspx   private void Button_Click_2(object sender, RoutedEventArgs e) { BackgroundWorker bw = new BackgroundWorker(); bw.DoWork += DoTheWork; bw.RunWorkerCompleted += Complete; bw.RunWorkerAsync(); } public void DoTheWork(object sender, DoWorkEventArgs e) { Thread.Sleep(500); } public void Complete(object sender, RunWorkerCompletedEventArgs e) { Title = "Hello"; }
  • 21. Access  UI  from  Thread   •  If  a  secondary  thread  aZempt  to  access  a  control  it  did  not   create  =>  run$me  error!     private void Button_Click_2(object sender, RoutedEventArgs e) { Thread thread = new Thread(new ThreadStart(ModifyTitle)); thread.Start(); } // Runtime Exception! public void ModifyTitle() { Title = "Hello World"; }
  • 22. Dispatcher  Class   •  Dispatcher  class  allows  you  to  modify  UI  from   secondary  thread   •  Read   –  hZp://msdn.microsog.com/en-­‐us/magazine/ cc163328.aspx  
  • 23. private void Button_Click_2(object sender, RoutedEventArgs e) { Thread t = new Thread(new ThreadStart(ModifyTitle)); t.Start(); } public void ModifyTitle() { Thread.Sleep(1000); // Change title to "Hello" Dispatcher.Invoke(new Action(ChangeTitle)); Thread.Sleep(1000); // Lambda Dispatcher.Invoke(() => this.Title = "World"); Thread.Sleep(1000); Dispatcher.Invoke(() => this.Title = ""); string newTitle = "Hello World!"; for (int i = 0; i < newTitle.Length; i++) { Thread.Sleep(100); Dispatcher.Invoke(() => this.Title += newTitle[i]); } } public void ChangeTitle() { this.Title = "Hello"; }
  • 24. Upda$ng  UI  and  Timer   •  Timer  calls  certain  method  in  interval   •  When  using  Threading.Timer  the  task  is  in   different  thread   –  Use  Dispatcher.Invoke  to  manipulate  the  UI  thread   •  When  using   Windows.Threading.DispatcherTimer,  the  task  in   in  UI  thread   –  If  this  performs  a  $me  consuming  task,  the  UI  will   freeze    
  • 26. Aync  Calls  Under  .NET  4.5   •  Two  new  keywords  to  simplify  threading  even   more   –  async  and  await   •  Compiler  will  generate  lot  of  code  when  using   these  keywords   •  async   –  Method  should  be  called  in  an  asynchronous  manner   automa$cally   •  await   –  Pause  current  thread  un$l  task  is  complete  
  • 27. async  and  await   •  In  .NET  4.5,  new  keywords:  async  and  await   •  Simplifies  threading,  generates  a  lot  of  code!   •  See:   –  hZp://blogs.msdn.com/b/pfxteam/archive/ 2012/04/12/10293335.aspx  
  • 28. namespace WpfApplication2 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private async void Button_Click_1(object sender, RoutedEventArgs e) { WebClient wb = new WebClient(); Task<string> result = wb.DownloadStringTaskAsync(new Uri("http://www.tamk.fi/")); string r = await result; Contents.Text = r; } } }
  • 30. Overview   •  System.IO  namespace  provides  number  of  classes   for  reading  and  wri$ng   •  Store  and  retrieve  primi$ve  types   –  BinaryReader,  BinaryWriter   •  Store  and  retrieve  text   –  StreamReader,  StreamWriter   •  Buffered  reading   –  BufferedStream   •  Helper  classes  like  File  (sta$c),  FileInfo  (object   reference  
  • 31. Reading  and  Wri$ng  Text   •  StreamWriter  and  StreamReader  use  useful   when  need  for  read  or  write  text   •  By  default:  Unicode   –  Can  be  changed:  pass  System.TextEncoding  object   reference   •  Methods   –  Write(),  WriteLine()  
  • 32. Wri$ng   class SaveText { public static void Main() { StreamWriter writer = File.CreateText("./textfile.txt"); // Nothing happens! Why? writer.WriteLine("Hello World!"); writer.WriteLine("Hello World!"); } }
  • 33. Wri$ng:  Flush  it!   using System; using System.IO; class SaveText { public static void Main() { StreamWriter writer = File.CreateText("./textfile.txt"); writer.WriteLine("Hello World!"); writer.WriteLine("Hello World!"); writer.Flush(); } }
  • 34. Wri$ng:  Stream  should  be  closed!   using System; using System.IO; class SaveText { public static void Main() { StreamWriter writer = File.CreateText("./textfile.txt"); writer.WriteLine("Hello World!"); writer.WriteLine("Hello World!"); writer.Flush(); writer.Close(); } }
  • 35. Wri$ng:  Flushing  is  done  when   closing!   using System; using System.IO; class SaveText { public static void Main() { StreamWriter writer = File.CreateText("./textfile.txt"); writer.WriteLine("Hello World!"); writer.WriteLine("Hello World!"); writer.Close(); } }
  • 36. Wri$ng:  using   using System; using System.IO; class ReadText { public static void Main() { using( StreamWriter writer = File.CreateText("./textfile.txt") ) { writer.WriteLine("Hello World!"); writer.WriteLine("Hello World!"); } } }
  • 37. Reading  Text   using System; using System.IO; class ReadText { public static void Main() { using( StreamReader reader = File.OpenText("./textfile.txt") ) { string input = null; while((input = reader.ReadLine()) != null) { Console.WriteLine(input); } } } }
  • 38. Reading  and  Wri$ng  Binary   using System; using System.IO; class ReadBinary { public static void Main() { using( BinaryWriter writer = new BinaryWriter( File.OpenWrite("./test.dat") ) ) { writer.Write(2.2); } using( BinaryReader reader = new BinaryReader( File.OpenRead("./test.dat") ) ) { Console.WriteLine(reader.ReadDouble()); } } }
  • 39. Watching  Files   •  Monitor  or  watch  files  using   FileSystemWatcher  class   •  Really  easy  to  implement   –  Which  folder  are  we  looking?   –  Set  up  things  to  listen   –  Add  Filters   –  Add  Event  Handlers   –  Start  listening  
  • 40. Example   using System; using System.IO; class Watcher { public static void Main() { FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = "/Users/pohjus/Desktop/tuhoa/"; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName; watcher.Filter = "*.txt"; watcher.Changed += (object source, FileSystemEventArgs e) => Console.Write("Changed"); watcher.Deleted += (object source, FileSystemEventArgs e) => Console.Write("Deleted"); watcher.EnableRaisingEvents = true; Console.Read(); } }
  • 41. Serializable   •  Serializa$on?  Store  an  state  of  the  object  into   stream!   •  Example:  Store  app  preferences  into  a  file.   Preference  informa$on  are  stored  in  object.   •  How?  Mark  a  class  as  Serializable  and  use   classes  to  store  and  open  the  object   •  You  can  save  the  object  as  binary  or  xml  (use   XMLSerializer  -­‐  class)  
  • 42. using  System;   using  System.IO;   using  System.Run$me.Serializa$on.FormaZers.Binary;     [Serializable]   class  Person   {    public  string  Name  {  get;  set;  }    public  int  Age  {  get;  set;  }   }   class  SerializableExample   {    public  sta$c  void  Main()    {      Person  jack  =  new  Person()  {  Name  =  "Jack",  Age  =  20  };        //  Let's  save  jack  as  binary      BinaryFormaZer  binFormat  =  new  BinaryFormaZer();        //  And  in  which  file?      using(FileStream  fs  =  new  FileStream("person.dat",  FileMode.Create))      {        //  Let's  do  it!        binFormat.Serialize(fs,  jack);      }    }   }    
  • 43. using  System;   using  System.IO;   using  System.Run$me.Serializa$on.FormaZers.Binary;     [Serializable]   class  Person   {    public  string  Name  {  get;  set;  }    public  int  Age  {  get;  set;  }   }     class  SerializableExample   {    public  sta$c  void  Main()    {      BinaryFormaZer  binFormat  =  new  BinaryFormaZer();        //  Deserialize!      using(FileStream  fs  =  new  FileStream("person.dat",  FileMode.Open))      {        Person  jack2  =  (Person)  binFormat.Deserialize(fs);        Console.WriteLine(jack2.Name);        Console.WriteLine(jack2.Age);      }    }   }  
  • 45. WPF   •  Windows  Presenta$on  Founda$on  (or  WPF)  is   a  computer-­‐sogware  graphical  subsystem  for   rendering  user  interfaces  in  Windows-­‐based   applica$ons   •  WPF  employs  XAML,  an  XML-­‐based  language,   to  define  and  link  various  UI  elements   •  See   –  hZp://msdn.microsog.com/en-­‐us/library/ ms752299.aspx