1

我需要听一个开放的 API,根据正确的数据我需要下载一些文件并处理它。我正在使用计时器每隔 x 秒自动发出一个下载请求,以保持连接处于活动状态,因此可以重复使用。

一共有3个组件:

  1. 家长班
  2. 监听类
  3. 定时器

父类在单独的线程上生成侦听器,并启动计时器。计时器和侦听器都调用父级的委托。

问题是,在每次从计时器下载时,连接都会被重用(从下载时间来看),但是当侦听器调用它时,它不是。

准系统代码:

using Timer = System.Timers.Timer;

namespace Hallelujah
{
    public delegate void downloadData(bool process, string url);
    public delegate void downloadDataInvoker(bool process, string url);

class Listener2
{
    downloadData _downloadData;
    public void start(string storeID, string shoes)
    {
        ServicePointManager.DefaultConnectionLimit = 500;
        ServicePointManager.Expect100Continue = false;
        ServicePointManager.MaxServicePoints = 0;

        _downloadData += new downloadData(downloadDataCb);

        Timer timer = new Timer(10000);
        timer.Elapsed += timer_Elapsed;
        timer.Enabled = true;

        Listen listenTool = new Listen();
        listenTool._downloadData += new downloadDataInvoker(invoker);

        Thread thread = new Thread(new ParameterizedThreadStart(listenTool.init));
        string[] str = { params };
        thread.Start(str);

        F1.updateStatus(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
    }

    void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _downloadData.Invoke(false, "example.com");
    }

    public void invoker(bool process, string url)
    {
        _downloadData.Invoke(process, url);
    }
    public void downloadDataCb(bool process, string url)
    {
        F1.updateStatus(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.KeepAlive = true;
        req.ProtocolVersion = HttpVersion.Version10;
        req.UnsafeAuthenticatedConnectionSharing = true;
        req.Pipelined = true;
        WebResponse res = req.GetResponse();
        Stream sr = res.GetResponseStream();
        //Reading response
        if (process)
        {
            F1.updateStatus("Downloaded  in " + t1.Seconds + " s " + t1.Milliseconds + "ms ");
        }
        else
            F1.updateStatus("Downloaded NULL(from timer) in " + t1.Seconds + " s " + t1.Milliseconds + "ms ");
    }

    public void updateStatusCB(string status)
    {
        F1.updateStatus(status);
    }

}
internal class Listen
{
    public downloadDataInvoker _downloadDataInvoker;
    public updateStatus _updateStatus;
    public bool ToListen = true;

    public void init(object objpass)
    {
        _updateStatus.Invoke(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString());

         while(ToListen){
            //When a match is found
            _downloadDataInvoker.Invoke(true, media_url);
        }


    }
}

知道为什么会这样吗?

4

1 回答 1

0

您在调用计时器事件时创建一个新的保持活动请求。

根据您的需要,有许多下载任务(通过 user_id?),您可以为每个任务创建一个保活请求,并开始异步请求,在回调事件中调用更新委托。

于 2013-11-14T04:50:42.400 回答