MNie
MNie

Reputation: 1367

InvalidOperationException occurs while token cancellation

I've a problem with passing cancellationtoken to the function. I get InvalidOperationException , "Calling thread cannot get permission to the object, because it belongs to another thread".

Here is my code.

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;
    }

Anyone know how to solve this problem with this error?

Upvotes: 1

Views: 292

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

I guess you get the exception because you read textBox.Text from another thread.

Try this:

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));
}

If this doesn't solves your problem provide more info about the exception.

Upvotes: 3

Related Questions