BackgroundWorker和剪贴板

use*_*764 6 c# wpf clipboard backgroundworker

我用一个简单的代码疯狂,我使用BackgroundWorker来自动执行基本操作.我应该向剪贴板添加内容吗?

在BackgroundWorker的方法中执行此代码后:

Clipboard.SetText (splitpermutation [i]);
Run Code Online (Sandbox Code Playgroud)

我得到一个错误,解释线程必须是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]);
        [...]
    }
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 6

您可以将其封送到UI线程以使其工作:

else
{
    [...]
    this.Dispatcher.BeginInvoke(new Action(() => Clipboard.SetText(splitpermutation[i])));
    [...]
}
Run Code Online (Sandbox Code Playgroud)

  • @codemann8 `Form.BeginInvoke` 应该为你做同样的事情。 (2认同)