我用一个简单的代码疯狂,我使用BackgroundWorker来自动执行基本操作.我应该向剪贴板添加内容吗?
Clipboard.SetText (splitpermutation [i]);
我得到一个错误,解释线程必须是STA,但我不明白该怎么做.
这里有更多代码:(不是全部)
private readonly BackgroundWorker worker = new BackgroundWorker(); private void btnAvvia_Click(object sender,RoutedEventArgs e) { count = lstview.Items.Count; startY = Convert.ToInt32(txtY.Text); startX = Convert.ToInt32(txtX.Text); finalY = Convert.ToInt32(txtFinalPositionY.Text); finalX = Convert.ToInt32(txtFinalPositionX.Text); incremento = Convert.ToInt32(txtIncremento.Text); pausa = Convert.ToInt32(txtPausa.Text); worker.WorkerSupportsCancellation = true; worker.RunWorkerAsync(); [...] } private void WorkFunction(object sender,DoWorkEventArgs e) { [...] if (worker.CancellationPending) { e.Cancel = true; break; } else { [...] Clipboard.SetText(splitpermutation[i]); [...] } }
解决方法
您可以将其封送到UI线程以使其工作:
else { [...] this.Dispatcher.BeginInvoke(new Action(() => Clipboard.SetText(splitpermutation[i]))); [...] }