C # collection: design a timeout blocking method

Source: Internet
Author: User

Sometimes we call a third-party method that will block the call. We need to consider a call timeout value. Generally, it is another way to add a join thread. Here is another way of thinking, however, this is not a complete solution. I hope you will discuss it more.
The following is a simple method, an execution method, an termination method, and a public delegate with the same signature as the execution method.

Class Myhelper
{
Public   Delegate   Int Executedelegate ( Int A );
Volatile   Bool _ Stopflag =   False ;
Public   Int Execute ( Int A)
{
Console. writeline ( " Execute method execution thread: {0} " , Thread. currentthread. gethashcode ());
Int I =   0 ;
While ( ! _ Stopflag)
{
Thread. Sleep (1000);
If(++I> =A)
ReturnI;
}
Return I;
}
Public   Void Abortexecute ()
{
_ Stopflag= True;
Console. writeline ("Terminate operation");
}
}

The excute method of the above class is blocked. If the input a parameter is a very large value,CodeIt will be blocked for a long time. If many client requests need to call this method, and your system implements multithreading, you can use the thread pool thread to process every user request, this is problematic. It will not be long before your thread pool will be exhausted. In this case, the following method can be used to add a timeout logic.

Private   Static   Void Invokeexcute ()
{
Myhelper H =   New Myhelper ();
Myhelper. executedelegate d = H. Execute;
Iasyncresult result = (Iasyncresult) D. begininvoke ( 5 ,
Delegate (Iasyncresult AR)
{< br> int temp = D. endinvoke (AR);
console. writeline ( " callback method execution thread: {0} " , thread. currentthread. gethashcode ();
console. writeline ( " the execution result is: {0} " , temp );
} , H );
Threadpool. registerwaitforsingleobject (result. asyncwaithandle,
Delegate ( Object State, Bool Timedout)
{
If (Timedout)
{
Try
{
(Myhelper) State). abortexecute ();
}
Catch (Exception ex)
{
Trace. traceerror ("An error occurred while terminating the operation: {0}", Ex );
}
Console. writeline ( " Timeout processing thread: {0}, timeout " , Thread. currentthread. gethashcode ());
}
Else
{
Console. writeline ("Timeout processing thread: {0}, not timeout", Thread. currentthread. gethashcode ());
}
} , H, 3000 , True );
}

The above sample code calls the excute method to be executed for 5 seconds, and we set a 3-second timeout time. In 3 seconds, we will terminate the call. In the future, if you want to write this method that may be blocked, add an abort method to terminate the operation and clean up the resources. For example, the httpwebrequest class is designed with an abort method.

However, if the blocking method is not written by you, provided by a third party, and the abort method is not available, the registerwaitforsingleobject timeout callback will be executed, however, the begininvoke execution delegate will continue to be executed in the thread pool, that is, it is still possible to exhaust the thread pool. My advice is for third-party methods that are not familiar, or a method that is known to be blocked. Do not let the thread pool call it. The thread pool is suitable for handling the fast return method.
Let's talk about another one. I implement a thread pool by myself. After a method execution in the thread pool times out, I will call the thread. abort to terminate this thread ,. net if a thread calls the unmanaged code, if you abort this thread, this thread will not immediately throw a threadabort exception, the exception will be thrown only when the unmanaged code returns the managed code. You still haven't solved the problem. In this case, we can say that socket. beginconnect is commonly used. Although it is asynchronous, it may block dozens of seconds. In fact, most of the time is on DNS resolution. This problem is basically not solved unless you rewrite the socket Implementation of windows. It seems that the socket is written in C ++. the connect function cannot control the timeout parameter either. It is implemented by using a message loop or multiple threads. It means that there is a registry key value, which does not seem to work very well.

Conclusion: I am very depressed and cannot find the answer. Maybe I think the problem is complicated.
Reference: http://morganchengmo.spaces.live.com/blog/cns! 9950ce918939932e! 1586. Entry
It is strongly recommended that Dudu automatically add hyperlinks to the text starting with HTTP, and I have to add them myself each time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.