帮助解决一个函数超出作用域的问题(C#)

3

我试图调用CancelAsync,虽然webClient的作用域已经超出了范围。

private void Download_Click(object sender, EventArgs e)
{
    WebClient webClient = new WebClient();
}


private void Button1_Click(object sender, EventArgs e)
{
    webClient.CancelAsync();
}

请问有人可以展示一下如何在此事件处理程序中调用webClient.CancelAsync()吗?

2个回答

6
你需要在你的类中存储WebClient

3
class ....
{
    WebClient webClient;

    private void Download_Click(object sender, EventArgs e)
    {
        webClient = new WebClient();
    }


    private void Button1_Click(object sender, EventArgs e)
    {
        webClient.CancelAsync();
    }

4
请注意,如果用户在未取消的情况下两次点击下载按钮,则会出现错误。 - CodesInChaos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接