如何在c#中停止对服务器的同步请求

本文关键字:服务器 同步 请求 | 更新日期: 2023-09-27 18:26:47

我知道以前有人问过这个问题,但我的情况不同。因为我不知道下面的代码是做什么的。我只是把它用作第三方开源工具。

我正在使用开源工具"UnityHTTP"从服务器获取响应。如果需要很长时间,我想取消响应请求。

我不是C#的专家,所以我无法理解该工具提供的代码中发生了什么。

如果有人能在这里帮我,我将不胜感激。

获取响应的代码如下

    private void GetResponse() {
        System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch();
        curcall.Start();
        try {
            var retry = 0;
            while (++retry < maximumRetryCount) {
                if (useCache) {
                    string etag = "";
                    if (etags.TryGetValue (uri.AbsoluteUri, out etag)) {
                        SetHeader ("If-None-Match", etag);
                    }
                }
                SetHeader ("Host", uri.Host);
                var client = new TcpClient ();
                client.Connect (uri.Host, uri.Port);
                using (var stream = client.GetStream ()) {
                    var ostream = stream as Stream;
                    if (uri.Scheme.ToLower() == "https") {
                        ostream = new SslStream (stream, false, new RemoteCertificateValidationCallback (ValidateServerCertificate));
                        try {
                            var ssl = ostream as SslStream;
                            ssl.AuthenticateAsClient (uri.Host);
                        } catch (Exception e) {
                            Debug.LogError ("Exception: " + e.Message);
                            return;
                        }
                    }
                    WriteToStream (ostream);
                    response = new Response ();
                    response.request = this;
                    state = RequestState.Reading;
                    response.ReadFromStream(ostream);
                }
                client.Close ();
                switch (response.status) {
                case 307:
                case 302:
                case 301:
                    uri = new Uri (response.GetHeader ("Location"));
                    continue;
                default:
                    retry = maximumRetryCount;
                    break;
                }
            }
            if (useCache) {
                string etag = response.GetHeader ("etag");
                if (etag.Length > 0)
                    etags[uri.AbsoluteUri] = etag;
            }
        } catch (Exception e) {
            Console.WriteLine ("Unhandled Exception, aborting request.");
            Console.WriteLine (e);
            exception = e;
            response = null;
        }
        state = RequestState.Done;
        isDone = true;
        responseTime = curcall.ElapsedMilliseconds;
        if ( completedCallback != null )
        {
            if (synchronous) {
                completedCallback(this);
            } else {
                // we have to use this dispatcher to avoid executing the callback inside this worker thread
                ResponseCallbackDispatcher.Singleton.requests.Enqueue( this );
            }
        }
        if ( LogAllRequests )
        {
#if !UNITY_EDITOR
            System.Console.WriteLine("NET: " + InfoString( VerboseLogging ));
#else
            if ( response != null && response.status >= 200 && response.status < 300 )
            {
                Debug.Log( InfoString( VerboseLogging ) );
            }
            else if ( response != null && response.status >= 400 )
            {
                Debug.LogError( InfoString( VerboseLogging ) );
            }
            else
            {
                Debug.LogWarning( InfoString( VerboseLogging ) );
            }
#endif
        }           
    }

我看得出来这与以下线路:-

 System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch();
        curcall.Start(); 

如何在c#中停止对服务器的同步请求

请求是使用TcpClient类发出的。它有两个属性ReceiveTimeout和SendTimeout。TcpClient初始化后,在连接之前为这两个属性设置所需的值:

var client = new TcpClient ();
client.ReceiveTimeout = 2000; // 2 seconds
client.SendTimeout = 2000;    // 2 seconds

这样做将导致TcpClient在超时时自动取消请求。

仅供参考-以下仅用于测量请求所用的时间。

 System.Diagnostics.Stopwatch curcall = new System.Diagnostics.Stopwatch();
 curcall.Start(); 
 ...
 responseTime = curcall.ElapsedMilliseconds;