Scanning with BackgroundWorker

Discussions about TWAIN & WIA scanning in GdPicture.NET using GdPictureImaging.
anwarcode
Posts: 3
Joined: Fri Feb 05, 2010 5:31 pm

Re: Scanning with BackgroundWorker

Post by anwarcode » Sat Feb 06, 2010 5:09 pm

Hi Loïc,

Here is what we are doing to run scanning in a background thread and poll for the scanning status in small intervals. Below code works inconsistently, when it fails last twain status returned from the Scanner is TwainStatus.TWAIN_SOURCE_ENABLED.

BackgroundWorker code, which calls Acquire(), and GetStatus() functions from DoWork thread. Acquire() function is called from a new Thread started inside BackgroundWorker thread, so that BackgroundWorker's worker thread can poll for the Scanner status at repeated intervals and update the UI.

I have sent an email to esupport (at) gdpicture (dot) com having the sample application attached which reproduces the problem; this may help you to figure out and narrow down the problem.

Regards
Anwar

Code: Select all

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using GdPicture;

namespace SampleScanTool
{
    public partial class Form1 : Form
    {
        GdPicture.GdPictureImaging _gdPictureImaging = new GdPicture.GdPictureImaging();
        public Form1()
        {
            InitializeComponent();
            _gdPictureImaging.SetLicenseNumber("XXXXXXXXXXXXXXXX");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (BackgroundWorker _worker = new BackgroundWorker())
            {
                var errorMessage = string.Empty;
                lblStatus.Text = GetStatus();
                _worker.WorkerSupportsCancellation = true;
                _worker.WorkerReportsProgress = true;
                _worker.DoWork += (s, ev) =>
                {
                    // Create a new thread and Scan documents
                    Thread t = new Thread(() =>
                    {
                        try
                        {
                            ev.Result = Acquire();
                        }

                        catch (Exception ex)
                        {
                            _worker.ReportProgress(0, ex.Message);
                        }
                    });

                    t.Start();

                    // Poll for the status of Scanner in 1000ms intervals

                    for (int i = 0; i < 1000; i++)
                    {
                        Thread.Sleep(500);
                        if (t.ThreadState == ThreadState.Stopped)
                        {
                            _worker.ReportProgress(0, "Scan job completed");
                            break;
                        }

                        if (t.ThreadState == ThreadState.Running)
                        {
                            _worker.ReportProgress(0, GetStatus()); // Get status of Scanner
                        }
                    }

                };

                _worker.RunWorkerCompleted += (s, ev) =>
                {
                    if (!ev.Cancelled && errorMessage == string.Empty)
                    {
                        if (ev.Result != null)
                        {
                            // handle result stream here
                        }
                    }
                    else
                    {
                        if (errorMessage != string.Empty)
                        {

                       }
                    }
                };

                _worker.ProgressChanged += (s, ev) =>
                {
                    lblStatus.Text = ev.UserState.ToString();
                };
                _worker.RunWorkerAsync();
            }

        }

        private Stream Acquire()
        {
            int imageId = 0;
            var file = Stream.Null; // Stream to save scanned document
            try
            {
                _gdPictureImaging.TwainSelectSource(IntPtr.Zero);
                if (_gdPictureImaging.TwainOpenDefaultSource(IntPtr.Zero))                
                {
                    _gdPictureImaging.TwainSetHideUI(true);
                    _gdPictureImaging.TwainSetIndicators(false);
                    imageId = _gdPictureImaging.TwainAcquireToGdPictureImage(IntPtr.Zero); // Acquire image
                    if (imageId != 0)
                    {
                        file = new MemoryStream();
                        _gdPictureImaging.SaveAsPDFStream(imageId, ref file, false, "", "", "", "", ""); // Save to Stream
                        _gdPictureImaging.ReleaseGdPictureImage(imageId);
                        MessageBox.Show("Image Acquired");
                    }

                    else
                    {
                        throw new ApplicationException("Failed to scan the document");
                    }

                    _gdPictureImaging.TwainUnloadSourceManager(IntPtr.Zero); // Close source
                    _gdPictureImaging.TwainCloseSource();
                    return file;
                }

                else
                {
                    throw new ApplicationException("Failed to open scanner source");
                }
            }

            catch (Exception)
            {
                throw; // rethrow exception to the UI
            }
        }

        private string GetStatus()
        {
            var statusMessage = String.Empty;
            try
            {
                var status = _gdPictureImaging.TwainGetState();
                switch (status)
                {
                    case TwainStatus.TWAIN_ERROR:
                        statusMessage = "Could not communicate with the scanner. Please verify that scanner is turned on and connected";
                        break;
                    case TwainStatus.TWAIN_PRESESSION:
                        statusMessage = "Scan tool is initializing and preparing to communicate with the scanner";
                        break;
                    case TwainStatus.TWAIN_SM_LOADED:
                        statusMessage = "Scan tool related system files have been loaded";
                        break;
                    case TwainStatus.TWAIN_SM_OPEN:
                        statusMessage = "Scan tool is checking for the available scanners";
                        break;
                    case TwainStatus.TWAIN_SOURCE_ENABLED:
                        statusMessage = "Scanner is working";
                        break;
                    case TwainStatus.TWAIN_SOURCE_OPEN:
                        statusMessage = "Scan tool is communicating to the scanner";
                        break;
                    case TwainStatus.TWAIN_TRANSFER_READY:
                        statusMessage = "Scan tool has detected that files are ready for transfer";
                        break;
                    case TwainStatus.TWAIN_TRANSFERRING:
                        statusMessage = "Scanner is transferring the scanned images";
                        break;
                };

                return statusMessage;
            }

            catch (Exception)
            {
                throw;
            }
        }
    }
}


User avatar
Loïc
Site Admin
Posts: 5673
Joined: Tue Oct 17, 2006 10:48 pm
Location: France
Contact:

Re: Scanning with BackgroundWorker

Post by Loïc » Sun Feb 07, 2010 12:07 am

Hi,

I think I solved your problem. i will send you a beta release tomorrow.

With best regards,

Loïc

Post Reply

Who is online

Users browsing this forum: No registered users and 2 guests