1

我在将 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;
    }

任何人都知道如何用这个错误解决这个问题?

4

1 回答 1

3

我猜你得到了例外,因为你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));
}

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

于 2014-05-17T16:03:03.270 回答