令牌取消时发生InvalidOperationException

时间:2014-05-17 15:56:51

标签: c# asynchronous task cancellation cancellationtokensource

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

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

1 个答案:

答案 0 :(得分: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));
}

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