Timeout pattern in C#

M

Max2006

Hi,

Is there any timeout pattern in C#?
I have a method that waits for an external resource and I don't want it to
wait for more than 10 seconds.

Thank you
Max
 
P

Peter Morris

Is there any timeout pattern in C#?
I have a method that waits for an external resource and I don't want it to
wait for more than 10 seconds.

What technique do you use to wait for the external resource?
 
W

William Stacey

One common way is to use Events for this. The top of method waits on this
reset event for x time and returns false if wait expires. The code depends
on how to shim this in around your resource logic or if you need a wrapper,
etc.

AutoResetEvent ar = new AutoResetEvent();
//...

public void CallResource()
{
if (ar.WaitOne(1000))
{
//resource finished
}
else
{
//timeout
}
}

--wjs
 
J

Jeff Johnson

One common way is to use Events for this.

And just to clarify, these are NOT the type of events you think of when you
think of "event handlers" or "Onxxx event raisers," but rather these events
are subclasses of the WaitHandle class, which is associated with thread
synchronization objects like semaphores, mutexes, etc.

(I know YOU know that, William; I just want to be sure everyone else does.)
 
M

Max2006

From my application perspective, I just call a c# function. The function
shouldn't take more than seconds.
 
H

Hongye Sun [MSFT]

Thanks for Pete, William and Jeff's help on this issue. Your answers are
very helpful.

Hi Max,

Thanks for your post. I am Hongye Sun [MSFT] and it is my pleasure to work
with you on this issue.

I think that you are asking for a best practice to set a timeout for
waiting for an operation completes, while the operation is waiting for an
external resource. Please let me know if there is anything missing in my
understanding.

A general pattern, which is widely used in .NET framework, is to create a
new thread to run the operation and the main thread waits for its
completion or timeout. If timeout is over, however it has not been
completed, the main thread will throw an TimeoutException. To implement
it, please write a method as below, which is a generic method for most of
the situations:
-------------------------------------------------------
static void CallAndWait(Action action, int timeout)
{
Thread subThread = null;
Action wrappedAction = () =>
{
subThread = Thread.CurrentThread;
action();
};

IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (((timeout != -1) && !result.IsCompleted) &&
(!result.AsyncWaitHandle.WaitOne(timeout, false) || !result.IsCompleted))
{
if (subThread != null)
{
subThread.Abort();
}

//TODO: close external resource.

throw new TimeoutException();
}
else
{
action.EndInvoke(result);
}
}
-------------------------------------------------------

Action is a delegate for method without parameters and return types. You
can also replace the Action type with your own delegate.

If this method does not work for you, please provide the following
information for us, so that we can provide you the right suggestion for
your specific scenario.
1. What is the external resource you are using?
2. Can you provide code snippet of the method?

Please let me know if you have anything unclear here. Thanks.

Regards,
Hongye Sun ([email protected], remove 'online.')
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/en-us/subscriptions/aa948868.aspx#notifications.

Note: MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 2 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions. Issues of this
nature are best handled working with a dedicated Microsoft Support Engineer
by contacting Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/en-us/subscriptions/aa948874.aspx
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.
 
P

Peter Morris

From my application perspective, I just call a c# function. The function
shouldn't take more than seconds.

What should happen after X seconds? Should the code stop running, or do you
just want your app to continue running and have that code complete in the
background? Also, is it your own function or a 3rd party one, and is the
function taking a long time due to processing or due to it waiting for
something else?
 
C

Cor Ligthert[MVP]

Max,

Keep in mind that (NT) Windows is a multitasking operating system (Windows
ME a multiprogramming one).

With both other tasks can influence any time related aspect of what is
running.

Cor
 
M

Max2006

Hi Pete,

The application should try to read a CSV file from a http address. if the
http address site is down (no response after 2 seconds), all numbers will be
considered null.
I have created the c# code that reads the CSV file from an external source.

I like to be able to extend the timeout approach to the other applications.
That is why I asked for "Timeout Pattern"

Thanks...Max
 
H

Hongye Sun [MSFT]

Hi Max,

Time-out operation is widely used in .NET Framework. For some specific
cases, you do not need to write your own code to handle time-out, because
NET Framework BCL has already implemneted it. For the other cases, please
refer to my previous post, which is one option to act as a generic time-out
solution. In this reply, I will tell which API in .NET Framework targets to
your problem.

For this case to get CSV file from a HTTP address, .NET Framework has
already had an existing API to do this job. It is
HttpWebRequest.GetResponse
(http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getrespon
se.aspx) and you can set the timeout value in its TimeOut property
(http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout.a
spx).

Following is a code sample:
-----------------------------------------------
try
{
WebRequest request = WebRequest.Create(@"<HTTP URL>");
if (request != null)
{
request.Timeout = 10000; // 10s

WebResponse response = request.GetResponse();
if (response != null)
{
s = response.GetResponseStream();
}
}
}
catch (Exception ex)
{
// Handle error
}

string content = null;
if (s != null)
{
StreamReader sr = new StreamReader(s);
content = sr.ReadToEnd();
}
-----------------------------------------------

In the GetResponse method, it creates a timer to trigger after 10 seconds.
If the http request is not completed after 10 seconds, the timer will abort
the request by throwing timout exception. Timer is also a widely used way
to detect time-out.

In addition, if you want to implement your own time-out method. Please also
refer the design pattern about time-out usage. It is documented at:
http://msdn.microsoft.com/en-us/library/1bff9tk5.aspx

Please let me know if you have any further question. I will be glad to help.

Regards,
Hongye Sun ([email protected], remove 'online.')
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

This posting is provided "AS IS" with no warranties, and confers no rights.
 
H

Hongye Sun [MSFT]

Hi Max,

Do my suggestions work on this issue? Please do not hesitate to let me know
if you need further help on it. Thanks.

Regards,
Hongye Sun ([email protected], remove 'online.')
Microsoft Online Community Support

Delighting our customers is our #1 priority. We welcome your comments and
suggestions about how we can improve the support we provide to you. Please
feel free to let my manager know what you think of the level of service
provided. You can send feedback directly to my manager at:
(e-mail address removed).

This posting is provided "AS IS" with no warranties, and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top