Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从未调用WebClient.DownloadProgressChanged_C#_.net - Fatal编程技术网

C# 从未调用WebClient.DownloadProgressChanged

C# 从未调用WebClient.DownloadProgressChanged,c#,.net,C#,.net,我在WebClient的DownloadProgressChanged事件中添加了一个事件处理程序,但它似乎从未启动。文件已成功下载,但未更新其进度 public class DownloadFile { private File file = null; public DownloadFile(File file) { this.file = file; } public void startDownloadThread()

我在WebClient的
DownloadProgressChanged
事件中添加了一个事件处理程序,但它似乎从未启动。文件已成功下载,但未更新其进度

public class DownloadFile
{
    private File file = null;

    public DownloadFile(File file)
    {
        this.file = file;
    }

    public void startDownloadThread()
    {
        Console.WriteLine("Starting Download : "+file.URL);

        var t = new Thread(() => DownloadThread(file));
        t.Start();
    }

    public Action<string> action_error_downloadFailed = Console.WriteLine;
    private void DownloadThread(File file) //Unnecessary argument but whatever ;D
    {
        try
        {
            string url = file.URL;
            string savepath = file.DestinationDir + "\\" + file.Filename;

            WebClient_B client = new WebClient_B();
            client.Proxy = null; //default to no proxy
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
            client.DownloadFile(url, savepath);

            Console.WriteLine("Download finished :" + file.Filename);
        }
        catch (Exception ex)
        {
            if (action_error_downloadFailed != null)
                action_error_downloadFailed("Download failed :"+ex.Message);
        }
    }

    private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {
        try
        {
            if (file.TotalSize == 0)
                file.TotalSize = (int)e.TotalBytesToReceive;
            file.CurrentSize = (int)e.BytesReceived;

            Form_DownloadManager.rebuildQueue();

            Console.WriteLine("{0}    downloaded {1} of {2} bytes. {3} % complete...",
            (string)e.UserState,
            e.BytesReceived,
            e.TotalBytesToReceive,
            e.ProgressPercentage);
        }
        catch (Exception ex) { Console.WriteLine("client_DownloadProgressChanged error : "+ex.Message); }
    }
}
公共类下载文件
{
私有文件=null;
公共下载文件(文件)
{
this.file=文件;
}
public void startDownloadThread()
{
WriteLine(“开始下载:+file.URL”);
var t=新线程(()=>下载线程(文件));
t、 Start();
}
公共操作操作错误下载失败=Console.WriteLine;
private void DownloadThread(File)//不必要的参数,但不管什么;D
{
尝试
{
字符串url=file.url;
字符串savepath=file.DestinationDir+“\\”+file.Filename;
WebClient_B client=新的WebClient_B();
client.Proxy=null;//默认为无代理
client.DownloadProgressChanged+=新的DownloadProgressChangedEventHandler(client\u DownloadProgressChanged);
client.DownloadFile(url、保存路径);
Console.WriteLine(“下载完成:“+file.Filename”);
}
捕获(例外情况除外)
{
如果(操作错误下载失败!=null)
操作错误下载失败(“下载失败:+ex.Message”);
}
}
private void client_DownloadProgressChanged(对象发送方,DownloadProgressChangedEventArgs e)
{
尝试
{
如果(file.TotalSize==0)
file.TotalSize=(int)e.TotalBytesToReceive;
file.CurrentSize=(int)e.BytesReceived;
表单_DownloadManager.rebuildQueue();
Console.WriteLine(“{0}下载了{1}个{2}字节。{3}%完成…”,
(字符串)e.UserState,
e、 收到的往事,
e、 TotalByTestorReceive,
e、 (百分比);
}
catch(异常ex){Console.WriteLine(“client_DownloadProgressChanged错误:“+ex.Message”);}
}
}
输出:

Starting Download : http://x.x.x/y/z.zip
'projectname.vshost.exe' (Managed (v4.0.30319)): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The thread '<No Name>' (0x3b8c) has exited with code 0 (0x0).
Download finished :z.zip
开始下载:http://x.x.x/y/z.zip
“projectname.vshost.exe”(托管(v4.0.30319)):加载的“C:\Windows\Microsoft.Net\assembly\GAC\U MSIL\System.Configuration\v4.0\U 4.0.0.0\Uuu b03f5f7f11d50a3a\System.Configuration.dll”跳过了加载符号。模块已优化,并且调试器选项“仅我的代码”已启用。
线程“”(0x3b8c)已退出,代码为0(0x0)。
下载完成:z.zip
我使用的是
WebClient\u B
,因为我的服务器一直拒绝下载请求,所以我不得不将useragent+cookiecontainer功能添加到
WebClient
类中。不过,事件也从未使用“standard”
WebClient
类触发。所以这不应该是问题所在。但无论如何

您必须使用异步版本下载文件,目前您使用的是分块同步版本

从for
WebClient.DownloadProgressChanged

在异步下载操作成功传输时发生 部分或全部数据

在您的情况下,这将是:

client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileAsync (url, savepath);

由于您的方法不会直接返回任何结果,因此重构不应该是一个问题,但请注意,在方法返回调用方之前,下载很可能尚未完成。

如果您希望同步使用WebClient,同时获得进度更新,您可以依赖此处详述的此方法


DownloadProgressChanged
DownloadFileCompleted
处理程序都是由调用
DownloadDataAsync
的线程执行的(根据我的测试)。您的意思是为lock的参数syncObj吗?Jay-e.UserState是HandleDownloadComplete中锁的正确参数。syncObject作为第三个参数传递给DownloadFileAsync,然后该方法将其作为AsyncCompletedEventArgs的UserState属性传递给HandleDownloadComplete事件处理程序,因此要在事件处理程序中访问它,您确实需要引用e.UserState。
lock(e.UserState)
Monitor.Pulse(e.UserState)
需要分别为
lock(args.UserState)
Monitor.Pulse(args.UserState)
,因为函数初始化中使用了
args
,而不是
e
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileAsync (url, savepath);
public void DownloadFile(Uri uri, string desintaion)
{
  using(var wc = new WebClient())
  {
    wc.DownloadProgressChanged += HandleDownloadProgress;
    wc.DownloadFileCompleted += HandleDownloadComplete;

    var syncObject = new Object();
    lock(syncObject)
    {
       wc.DownloadFileAsync(sourceUri, destination, syncObject);
       //This would block the thread until download completes
       Monitor.Wait(syncObject);
    }
  }

  //Do more stuff after download was complete
}

public void HandleDownloadComplete(object sender, AsyncCompletedEventArgs args)
{
   lock(e.UserState)
   {  
      //releases blocked thread
      Monitor.Pulse(e.UserState);
   }
}


public void HandleDownloadProgress(object sender, DownloadProgressChangedEventArgs args)
{
  //Process progress updates here
}