title: TwainDotNet Scanning using TWAIN with BackgroundWorker
body: <p>Has anyone tried <a href="http://code.google.com/p/twaindotnet/" rel="nofollow noreferrer">TwainDotNet</a> for scanning with TWAIN API calls from .NET? Though it works well usually I've some issues with it when used along with WPF application using MVVM. Basically I'm calling Twain scanning functions from a Service, which in turn uses a BackgroundWorker.</p>
  
  <pre><code>List&lt;BitmapSource&gt; bitmapSources = new List&lt;BitmapSource&gt;();
  Twain twain = new Twain(new WpfWindowMessageHook(_window));
  ScanSettings settings = new ScanSettings() { ShowTwainUI = false };
  using (BackgroundWorker worker = new BackgroundWorker())
  {
      worker.DoWork += (sndr, evnt) =&gt;
      {
          AutoResetEvent waitHandle = new AutoResetEvent(false);
          EventHandler scanCompleteHandler = (se, ev) =&gt; { waitHandle.Set(); };
          twain.ScanningComplete += scanCompleteHandler;
          twain.StartScanning(settings);
          waitHandle.WaitOne();
  
          if (twain.Images.Count &gt; 0)
          {
              foreach (var image in twain.Images)
              {
                  BitmapSource bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(new Bitmap(image).GetHbitmap(),
                      IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
                  bitmapSources.Add(bitmapSource);
              }
          }
      };
      worker.RunWorkerCompleted += (sndr, evnt) =&gt; { image1.Source = bitmapSources[0]; };
      worker.RunWorkerAsync();
  }
  </code></pre>
  
  <p>ScanningComplete event handler is never fired when we are working with a BackgroundWorker. Any suggestions to resolve this issue?</p>