winforms 当一个任务添加到列表时,从另一个任务打印字符串列表

t40tm48m  于 2022-11-17  发布在  其他
关注(0)|答案(1)|浏览(138)

我有一个交互,当我执行操作(日志)时,我从一个任务添加到一个列表,我希望一个win forms后台工作进程在运行时打印新添加到该列表的内容
对api的调用是

List<string> log = new List();
obj.PerformOperation(value, out log);

我希望我可以打印到GUI文本框的新增加的列表,我累了这样的东西,但它不工作

private void configWorker_DoWork(object sender, DoWorkEventArgs e)
{
    List<string> log = new List<string>();
    logWorker.RunWorkerAsync(log);
    obj.PerformOperation(value, out log);
}

private void logWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;
    List<string> log = e.Argument as List<string>;
    int log_index = 0;
    do
    {
        this.Invoke(new MethodInvoker(delegate ()
        {
            if (log.Count > log_index)
            {
                do
                {
                    logTextBox.RecordLog(log[log_index++]);
                } while (log_index < log.Count);
            }
        }));
    } while (!worker.CancellationPending);
}

后台worker循环,但它似乎没有更新文本框。有人能帮助我如何执行此操作而不修改api调用吗?
谢谢你:)

knsnq2tg

knsnq2tg1#

你可能想尝试观察。也许下面给你一些想法?得到通知,打印结果。不需要不断地在后台迭代收集。

private void RunIt()
{
    var cancelTokenSource = new CancellationTokenSource();
    var token = cancelTokenSource.Token;

    var things = new ObservableCollection<string>();
    things.CollectionChanged += (sender, args) =>
    {
        if (args.Action == NotifyCollectionChangedAction.Add)
            foreach (var item in args.NewItems)
                BeginInvoke((Action) (() => logTextBox.Text += $@"{item}{Environment.NewLine}"));
    };
    Task.Factory.StartNew(() =>
    {
        while (!token.IsCancellationRequested)
        {
            things.Add(DateTime.Now.Ticks.ToString());
            Thread.Sleep(250);
        }
    }, token);
}

相关问题