【问题标题】:InvalidOperationException occurs while token cancellation取消令牌时发生 InvalidOperationException
【发布时间】:2014-05-17 15:56:51
【问题描述】:

我在将 canceltoken 传递给函数时遇到问题。我得到 InvalidOperationException ,“调用线程无法获得对象的权限,因为它属于另一个线程”。

这是我的代码。

private CancellationTokenSource cts;
private CancellationToken ct;
public MainWindow()
    {
        InitializeComponent();
        client = new WebClient();
        cts = new CancellationTokenSource();
        ct = cts.Token;
    }
private void one_Click(object sender, RoutedEventArgs e)
    {
        cts = new CancellationTokenSource();
        ct = cts.Token;
        Task myTask = Task.Run(() => Save(textBox.Text, ct));
    }
private void Save(string url, CancellationToken ct)
    {
        //var url = ThirdAddressTextBox.Text;

        var html = client.DownloadString(url);
        var doc = new HtmlDocument();
        doc.LoadHtml(html);

        var imageNodesList =
            doc.DocumentNode.SelectNodes("//img")
            .Where(
                    x =>
                        x.Name == "img")
                .Select(x => x)
                .ToList();
        int temp= 0;
        foreach (var htmlNode in imageNodesList)
        {
            if (ct.IsCancellationRequested)
            {
                return;
            }
            client.DownloadFile(new Uri(htmlNode.Attributes["src"].Value), @"C:\Users\" + temp+ ".jpg");
            ++licznik;
        }
        client.DownloadFile(new Uri(url), @"C:\Users\");
        return;
    }

有谁知道如何解决这个错误?

【问题讨论】:

    标签: c# asynchronous task cancellation cancellationtokensource


    【解决方案1】:

    我猜你得到了例外,因为你从另一个线程中读取了textBox.Text

    试试这个:

    private void one_Click(object sender, RoutedEventArgs e)
    {
        cts = new CancellationTokenSource();
        ct = cts.Token;
        string url = textBox.Text;//Read it in UI thread itself
        Task myTask = Task.Run(() => Save(url, ct));
    }
    

    如果这不能解决您的问题,请提供有关异常的更多信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-28
      • 1970-01-01
      • 2019-09-10
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多