.Net中异步操作超时的设置方法.

下面的示例使用 BeginGetResponse 方法对 Internet 资源发出异步请求。 注意 在异步请求中,客户端应用程序负责实现自己的超时机制。下面的示例显示如何实现这一点。

using System;
using System.Net;
using System.IO;
using System.Text;
using System.Threading;


public class RequestState
{
  // This class stores the State of the request.
  const int BUFFER_SIZE = 1024;
  public StringBuilder requestData;
  public byte[] BufferRead;
  public HttpWebRequest request;
  public HttpWebResponse response;
  public Stream streamResponse;
  public RequestState()
  {
    BufferRead = new byte[BUFFER_SIZE];
    requestData = new StringBuilder("");
    request = null;
    streamResponse = null;
  }
}


class HttpWebRequest_BeginGetResponse
{
  public static ManualResetEvent allDone= new ManualResetEvent(false);
  const int BUFFER_SIZE = 1024;
  const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout
 
  // Abort the request if the timer fires.
  private static void TimeoutCallback(object state, bool timedOut) {
      if (timedOut) {
          HttpWebRequest request = state as HttpWebRequest;
          if (request != null) {
              request.Abort();
          }
      }
  }

  static void Main()
  { 
  
    try
    {
      // Create a HttpWebrequest object to the desired URL.
      HttpWebRequest myHttpWebRequest= (HttpWebRequest)WebRequest.Create("http://www.contoso.com");

   
  /**
    * If you are behind a firewall and you do not have your browser proxy setup
    * you need to use the following proxy creation code.

      // Create a proxy object.
      WebProxy myProxy = new WebProxy();

      // Associate a new Uri object to the _wProxy object, using the proxy address
      // selected by the user.
      myProxy.Address = new Uri("http://myproxy");
      
       
      // Finally, initialize the Web request object proxy property with the _wProxy
      // object.
      myHttpWebRequest.Proxy=myProxy;
    ***/

      // Create an instance of the RequestState and assign the previous myHttpWebRequest
      // object to it's request field. 
      RequestState myRequestState = new RequestState(); 
      myRequestState.request = myHttpWebRequest;


      // Start the asynchronous request.
      IAsyncResult result=
        (IAsyncResult) myHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback),myRequestState);

      // this line impliments the timeout, if there is a timeout, the callback fires and the request becomes aborted
      ThreadPool.RegisterWaitForSingleObject (result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), myHttpWebRequest, DefaultTimeout, true);

      // The response came in the allowed time. The work processing will happen in the
      // callback function.
      allDone.WaitOne();
     
      // Release the HttpWebResponse resource.
      myRequestState.response.Close();
    }
    catch(WebException e)
    {
      Console.WriteLine("/nMain Exception raised!");
      Console.WriteLine("/nMessage:{0}",e.Message);
      Console.WriteLine("/nStatus:{0}",e.Status);
      Console.WriteLine("Press any key to continue..........");
    }
    catch(Exception e)
    {
      Console.WriteLine("/nMain Exception raised!");
      Console.WriteLine("Source :{0} " , e.Source);
      Console.WriteLine("Message :{0} " , e.Message);
      Console.WriteLine("Press any key to continue..........");
      Console.Read();
    }
  }
  private static void RespCallback(IAsyncResult asynchronousResult)
  { 
    try
    {
      // State of request is asynchronous.
      RequestState myRequestState=(RequestState) asynchronousResult.AsyncState;
      HttpWebRequest  myHttpWebRequest=myRequestState.request;
      myRequestState.response = (HttpWebResponse) myHttpWebRequest.EndGetResponse(asynchronousResult);
     
      // Read the response into a Stream object.
      Stream responseStream = myRequestState.response.GetResponseStream();
      myRequestState.streamResponse=responseStream;
     
      // Begin the Reading of the contents of the HTML page and print it to the console.
      IAsyncResult asynchronousInputRead = responseStream.BeginRead(myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
      return;
    }
    catch(WebException e)
    {
      Console.WriteLine("/nRespCallback Exception raised!");
      Console.WriteLine("/nMessage:{0}",e.Message);
      Console.WriteLine("/nStatus:{0}",e.Status);
    }
    allDone.Set();
  }
  private static  void ReadCallBack(IAsyncResult asyncResult)
  {
    try
    {

    RequestState myRequestState = (RequestState)asyncResult.AsyncState;
    Stream responseStream = myRequestState.streamResponse;
    int read = responseStream.EndRead( asyncResult );
    // Read the HTML page and then print it to the console.
    if (read > 0)
    {
      myRequestState.requestData.Append(Encoding.ASCII.GetString(myRequestState.BufferRead, 0, read));
      IAsyncResult asynchronousResult = responseStream.BeginRead( myRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), myRequestState);
      return;
    }
    else
    {
      Console.WriteLine("/nThe contents of the Html page are : ");
      if(myRequestState.requestData.Length>1)
      {
        string stringContent;
        stringContent = myRequestState.requestData.ToString();
        Console.WriteLine(stringContent);
      }
      Console.WriteLine("Press any key to continue..........");
      Console.ReadLine();
     
      responseStream.Close();
    }

    }
    catch(WebException e)
    {
      Console.WriteLine("/nReadCallBack Exception raised!");
      Console.WriteLine("/nMessage:{0}",e.Message);
      Console.WriteLine("/nStatus:{0}",e.Status);
    }
    allDone.Set();

  }
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
.net C#线程超时的解决方案,使用的时候在被调线程入口调用一下这个方法就可以。更多详细代码见附件 Report.RegisterThread(Report.GetCurrentWin32ThreadID(),Thread.CurrentThread); #region 获取当取线程的ThreadID [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)] public static extern Int32 GetCurrentWin32ThreadID(); #endregion #region 登记访问任务子线程 /// /// 访问任务子线程 /// public static Hashtable TaskThreadIDTable = Hashtable.Synchronized(new Hashtable()); private static int[] TaskThreadIDs { get { int[] IDs = new int[TaskThreadIDTable.Keys.Count]; TaskThreadIDTable.Keys.CopyTo(IDs, 0); return IDs; } } public static void RegisterThread(int _threadid, System.Threading.Thread thread) { if (!TaskThreadIDTable.ContainsKey(_threadid)) TaskThreadIDTable.Add(_threadid, thread); if (!ExitInvalidThreadLoopRunning) { Thread ExitInvalidThreadLoopThread = new Thread(new ThreadStart(ExitInvalidThreadLoop)); ExitInvalidThreadLoopThread.Priority = ThreadPriority.AboveNormal; ExitInvalidThreadLoopThread.Start(); } } #endregion #region 关闭,退出超时的用户线程 private static DateTime ExitInvalidThreadLoop_LastRunTime = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0)); private static bool ExitInvalidThreadLoopRunning { get { return DateTime.Now.Subtract(ExitInvalidThreadLoop_LastRunTime).TotalMinutes 10) { try { Thread thread = (Thread)TaskThreadIDTable[t.Id]; thread.Abort(); } catch { } t.Dispose(); } } #endregion } #endregion
### 回答1: .NET Socket异步客户端辅助类是一种用于简化异步网络编程的工具,它可以帮助开发者更轻松地创建和管理客户端与服务器之间的通信。下面是一些关于.NET Socket异步客户端辅助类的重要信息。 首先,.NET Socket异步客户端辅助类提供了一种方便的方法来实现异步通信,使开发者能够在不阻塞主线程的情况下进行网络通信。通过使用异步操作,可以提高应用程序的性能和响应能力。 其次,这个辅助类提供了一系列方法和事件,用于与服务器进行连接、发送和接收数据。例如,它提供了一个ConnectAsync方法,可以异步连接服务器。它还提供了一个SendAsync方法,可以异步发送数据到服务器。另外,它还提供了一个ReceiveAsync方法,可以异步接收来自服务器的数据。 除了发送和接收数据,该辅助类还提供了一些其他功能。例如,它提供了一个用于断开与服务器的连接的DisconnectAsync方法。它还提供了一个用于设置和获取服务器的IP地址和端口的属性。 最后,这个辅助类还具有一些事件,用于处理与服务器之间的异步操作。例如,它提供了一个用于处理连接成功的事件,一个用于处理接收到数据的事件,以及一个用于处理发生错误的事件。通过使用这些事件,开发者可以编写处理不同情况下的网络通信的代码逻辑。 总而言之,.NET Socket异步客户端辅助类是.NET框架提供的一个工具,用于简化异步网络编程。通过它,开发者可以更方便地创建和管理客户端与服务器之间的通信,从而提高应用程序的性能和响应能力。 ### 回答2: .NET Socket 异步客户端辅助类可以帮助开发人员更便捷地创建异步网络客户端应用程序。该辅助类是基于.NET Socket 类库的,通过使用异步方法和事件处理器,提供了更高效和可靠的网络通信功能。 首先,通过该辅助类,我们可以方便地创建与服务器端的连接。它提供了异步连接方法,可以在不阻塞主线程的情况下与服务器建立连接。这样可以允许应用程序同时处理其他任务,提高程序的并发性和性能。 其次,辅助类还具备异步发送和接收数据的功能。通过异步发送方法,我们可以将数据发送到服务器,并在发送完成时得到相应的通知。而异步接收方法则可以让我们在后台处理接收到的数据,而不会阻塞程序的其他操作。这使得我们能够实现同时发送和接收数据的功能,提高了应用程序的响应速度。 此外,该辅助类还提供了事件处理器,用于处理连接、发送和接收等过程发生的异步事件。例如,我们可以注册连接成功时的事件处理器,以便在连接建立完成后做进一步的处理。同样,我们还可以处理接收到数据的事件,根据实际业务需求进行相应的处理。 总而言之,.NET Socket 异步客户端辅助类为开发人员提供了一种方便、高效和可靠的方式来构建异步网络客户端应用程序。通过它,我们可以简化开发过程,提高程序的性能和可维护性,实现更好的用户体验。 ### 回答3: .NET Socket异步客户端辅助类是在使用.NET框架进行网络编程时提供的一种工具,用于创建和管理异步客户端网络连接。这些辅助类提供了简化操作方法和事件,使开发人员能够更方便地在应用程序实现异步通信。 首先,它包括一个异步客户端类,该类提供了用于与服务器建立连接、发送和接收数据的方法。它包装了系统级的Socket类,并且通过使用异步方法,可以避免阻塞应用程序线程。 其次,异步客户端辅助类还提供了一些事件,用于处理网络连接过程的各种情况。例如,它提供了一个连接已建立的事件,可以在连接成功时触发,以便应用程序可以执行特定的操作。同样,它还提供了接收到数据的事件,可以在收到来自服务器的数据时触发,使我们能够对数据进行处理。 此外,辅助类还提供了一些属性和方法,用于配置和管理异步操作。例如,我们可以设置接收缓冲区的大小,以便更高效地处理大量数据。还可以指定连接超时时间,以防止长时间无法建立连接。 总之,.NET Socket异步客户端辅助类是.NET框架提供的一种简化网络编程的工具。它通过封装底层的Socket类,提供了一组易于使用的方法和事件,使开发人员能够更轻松地实现异步通信。使用这些辅助类,我们可以更加高效和可靠地处理网络连接,为我们的应用程序带来更好的用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值