대부분의 서비스 개체는 별도의 하드웨어 판독기 스레드를 시작하여 하드웨어 이벤트에 비동기적으로 응답할 수 있어야 합니다. 서비스 개체는 서비스 지점(POS) 애플리케이션과 하드웨어 간의 링크입니다. 따라서 서비스 개체는 애플리케이션에서 계속 사용할 수 있는 동안 연결된 하드웨어에서 데이터를 읽어야 합니다.
이 섹션에서는 다중 스레드 서비스 개체에 필요한 코드를 구현하는 한 가지 방법을 보여줍니다.
요구 사항
이 코드를 컴파일하려면 애플리케이션에 System.Threading 네임스페이스에 대한 참조가 포함되어야 합니다.
아래 샘플에서는 서비스 개체 구현에서 사용할 수 있지만 자체적으로 컴파일하거나 실행하지 않는 스레딩 도우미 클래스를 구현합니다.
데모
이 샘플에서는 서비스 개체가 스레딩을 사용하여 하드웨어 이벤트 모니터링을 비동기적으로 지원하는 방법을 보여줍니다. 샘플 코드는 서비스 개체에 기본 스레딩 지원을 추가하는 데 사용할 수 있는 스레드 도우미 클래스를 구현합니다.
이 섹션에 제공된 스레드 도우미 클래스를 사용하려면 아래 코드에 포함된 ServiceObjectThreadHelper에서 파생된 클래스를 만들고 다음 메서드를 구현해야 합니다.
ServiceObjectThreadOpen 이 메서드는 초기화가 완료된 후 스레드 도우미 클래스의 OpenThread 메서드에서 호출됩니다. 여기에서 하드웨어별 초기화 코드를 구현합니다. 이 메서드는 virtual입니다. 기본 구현은 단순히 반환합니다.
ServiceObjectThreadClose 이 메서드는 스레드 도우미 개체가 스레드를 종료하거나 Dispose 메서드를 호출할 때 호출되며 디바이스와 관련된 관리되지 않는 핸들 또는 기타 리소스를 해제하는 데 사용해야 합니다. 이 메서드는 virtual입니다. 기본 구현은 단순히 반환합니다.
ServiceObjectProcedure 이 메서드는 모든 초기화가 수행되고 스레드가 성공적으로 시작되면 호출됩니다. 이 메서드는 추상이며 스레드 도우미 클래스에서 파생된 클래스에서 구현되어야 합니다. ServiceObjectProcedure 메서드는 단일 인수인 ManualEvent 핸들을 사용합니다. 이 핸들이 설정되면 스레드 프로시저가 종료되어야 합니다. 이 작업은 While 루프 내에서 ManualEvent.WaitOne을 호출하여 수행합니다. 예를 들어:
while (true) { // Wait for a hardware event or the thread stop event. // Test to see if the thread terminated event is set and // exit the thread if so. if (ThreadStopEvent.WaitOne(0, false)) { break; } // The thread is not terminating, so it must be a // a hardware event. }
예제
using System;
using System.Threading;
using Microsoft.PointOfService;
namespace Samples.ServiceObjects.Advanced
{
// The following code implements a thread helper class.
// This class may be used by other Point Of Service
// samples which may require a separate thread for monitoring
// hardware.
public abstract class ServiceObjectThreadHelper : IDisposable
{
// The thread object which will wait for data from the POS
// device.
private Thread ReadThread;
// These events signal that the thread is starting or stopping.
private AutoResetEvent ThreadTerminating;
private AutoResetEvent ThreadStarted;
// Keeps track of whether or not a thread should
// be running.
bool ThreadWasStarted;
public ServiceObjectThreadHelper()
{
// Create events to signal the reader thread.
ThreadTerminating = new AutoResetEvent(false);
ThreadStarted = new AutoResetEvent(false);
ThreadWasStarted = false;
// You need to handle the ApplicationExit event so
// that you can properly clean up the thread.
System.Windows.Forms.Application.ApplicationExit +=
new EventHandler(Application_ApplicationExit);
}
~ServiceObjectThreadHelper()
{
Dispose(true);
}
public virtual void ServiceObjectThreadOpen()
{
return;
}
public virtual void ServiceObjectThreadClose()
{
return;
}
// This is called when the thread starts successfully and
// will be run on the new thread.
public abstract void ServiceObjectThreadProcedure(
AutoResetEvent ThreadStopEvent);
private bool IsDisposed = false;
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
try
{
if (disposing == true)
{
CloseThread();
}
}
finally
{
IsDisposed = true;
}
}
}
public void Dispose()
{
Dispose(true);
// This object has been disposed of, so no need for
// the GC to call the finalization code again.
GC.SuppressFinalize(this);
}
public void OpenThread()
{
try
{
// Check to see if this object is still valid.
if (IsDisposed)
{
// Throw system exception to indicate that
// the object has already been disposed.
throw new ObjectDisposedException(
"ServiceObjectSampleThread");
}
// In case the application has called OpenThread
// before calling CloseThread, stop any previously
// started thread.
SignalThreadClose();
ServiceObjectThreadOpen();
// Reset event used to signal the thread to quit.
ThreadTerminating.Reset();
// Reset the event that used by the thread to signal
// that it has started.
ThreadStarted.Reset();
// Create the thread object and give it a name. The
// method used here, ThreadMethod, is a wrapper around
// the actual thread procedure, which will be run in
// the threading object provided by the Service
// Object.
ReadThread = new Thread(
new ThreadStart(ThreadMethod));
// Set the thread background mode.
ReadThread.IsBackground = false;
// Finally, attempt to start the thread.
ReadThread.Start();
// Wait for the thread to start, or until the time-out
// is reached.
if (!ThreadStarted.WaitOne(3000, false))
{
// If the time-out was reached before the event
// was set, then throw an exception.
throw new PosControlException(
"Unable to open the device for reading",
ErrorCode.Failure);
}
// The thread has started successfully.
ThreadWasStarted = true;
}
catch (Exception e)
{
// If an error occurred, be sure the new thread is
// stopped.
CloseThread();
// Re-throw to let the application handle the
// failure.
throw;
}
}
private void SignalThreadClose()
{
if(ThreadTerminating != null && ThreadWasStarted)
{
// Tell the thread to terminate.
ThreadTerminating.Set();
// Give the thread a few seconds to end.
ThreadStarted.WaitOne(10000, false);
// Mark the thread as being terminated.
ThreadWasStarted = false;
}
}
public void CloseThread()
{
// Signal the thread that it should stop.
SignalThreadClose();
// Call back into the SO for any cleanup.
ServiceObjectThreadClose();
}
private void Application_ApplicationExit(
object sender,
EventArgs e)
{
SignalThreadClose();
}
// This is the method run on the new thread. First it signals
// the caller indicating that the thread has started
// correctly. Next, it calls the service object's thread
// method which will loop waiting for data or a signal
// to close.
private void ThreadMethod()
{
try
{
// Set the event to indicate that the thread has
// started successfully.
ThreadStarted.Set();
// Call into the thread procedure defined by the
// Service Object.
ServiceObjectThreadProcedure(ThreadTerminating);
// Signal that the thread procedure is exiting.
ThreadStarted.Set();
}
catch (Exception e)
{
Logger.Info("ServiceObjectThreadHelper",
"ThreadMethod Exception = " + e.ToString());
throw;
}
}
}
}
참고 항목
작업
기타 리소스
.NET