我在将 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;
}
任何人都知道如何用这个错误解决这个问题?