M
Morgan Cheng
In order to arrange a time-out operation, I make the task running in a
worker thread; and wait in main thread with AutoResetEvent help. The
code is like below.
AutoResetEvent ev = new AutoResetEvent();
if ( !ThreadPool.QueueUserWorkItem(WorkerProc, ev) )
{
throw new ApplicationException("fail to queue task");
}
ev.WaitOne(5000, false); //timeout == 5000 ms
public void WorkProc(object state)
{
AutoResetEvent ev = state as AutoResetEvent;
// do some timecosting job
.....
ev.Set();
}
However, AutoResetEvent inherits from WaitHandle which inherits from
IDisposable. So, I change mo code to
using (AutoResetEvent ev = new AutoResetEvent() )
{
if ( !ThreadPool.QueueUserWorkItem(WorkerProc, ev) )
{
throw new ApplicationException("fail to queue task");
}
ev.WaitOne(5000, false); //timeout == 5000 ms
};
public void WorkProc(object state)
{
AutoResetEvent ev = state as AutoResetEvent;
// do some timecosting job
.....
ev.Set(); // ObjectDisposedException may be thrown here.
}
While debugging, ObjectDisposedException may be thrown from WokProc,
because AutoResetEvent might have been disposed in main thread. So,
have to embrace ev.Set with try{} catch {} to get
ObjectDisposedException. It is ugly code.
So, what is best solution?
worker thread; and wait in main thread with AutoResetEvent help. The
code is like below.
AutoResetEvent ev = new AutoResetEvent();
if ( !ThreadPool.QueueUserWorkItem(WorkerProc, ev) )
{
throw new ApplicationException("fail to queue task");
}
ev.WaitOne(5000, false); //timeout == 5000 ms
public void WorkProc(object state)
{
AutoResetEvent ev = state as AutoResetEvent;
// do some timecosting job
.....
ev.Set();
}
However, AutoResetEvent inherits from WaitHandle which inherits from
IDisposable. So, I change mo code to
using (AutoResetEvent ev = new AutoResetEvent() )
{
if ( !ThreadPool.QueueUserWorkItem(WorkerProc, ev) )
{
throw new ApplicationException("fail to queue task");
}
ev.WaitOne(5000, false); //timeout == 5000 ms
};
public void WorkProc(object state)
{
AutoResetEvent ev = state as AutoResetEvent;
// do some timecosting job
.....
ev.Set(); // ObjectDisposedException may be thrown here.
}
While debugging, ObjectDisposedException may be thrown from WokProc,
because AutoResetEvent might have been disposed in main thread. So,
have to embrace ev.Set with try{} catch {} to get
ObjectDisposedException. It is ugly code.
So, what is best solution?