Denis Kulagin
Denis Kulagin

Reputation: 8916

C#: wrap syncronous call to introduce timeout

I have a syncronous call:

var answer = obj.SyncCall(question);

It may execute for indefinitely long, but I would like to limit it's execution time:

// throws TimeoutException if not complete in 1000ms
var answer = obj.SyncCall(question, 1000);

How to wrap a sync call into thread to allow described behaviour?

Upvotes: 1

Views: 548

Answers (1)

Jan Novák
Jan Novák

Reputation: 594

.NET 4.5: You can run a Task and wait for it for your defined time:

Task.Run(() => { answer = obj.SyncCall(question) }).Wait(1000);

Pre .NET 4.5: You can use the same approach, just using ThreadPool and sync object:

ManualResetEvent evt = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem((object o) =>
{
  answer = obj.SyncCall(question);
  evt.Set();
});
evt.WaitOne(1000);

Upvotes: 3

Related Questions