c# - "The subprocess making the call can not access this object because the owner is another thread"异常异步/等待 WPF C#

标签 c# .net wpf xaml async-await

我有这个代码:

SecondLog.Opacity = 1;
List<Reporte> Reportes =await Task.Run(() => db_data.TraerReportes(Environment.MachineName, PickFecha.SelectedDate.Value.Date.ToShortDateString()));
    if (Reportes.Count  != 0)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("Nombre del Proceso");
        dt.Columns.Add("Tiempo Activo");
        dt.Columns.Add("Hora del Ultimo Reporte");
        foreach (Reporte R in Reportes)
        {
            TimeSpan a = TimeSpan.FromSeconds(R.TiempoActivo);
            var Columna = dt.NewRow();
            Columna["t1"] = R.NombreProceso;
            Columna["t2"] = a.ToString(@"hh\:mm\:ss");
            Columna["t3"] = R.Fecha;

            dt.Rows.Add(Columna);
            }
            GridReportes.DataContext = dt.DefaultView;
        }

这将返回:

The subprocess making the call can not access this object because the owner is another thread" exception at line 2 ( List Reportes =await Task.Run(() => db_SpixService.TraerReportes(Environment.MachineName, PickFecha.SelectedDate.Value.Date.ToShortDateString()));)

这是为什么?

最佳答案

// this is the part that cannot run on another thread, so prepare it
string param = PickFecha.SelectedDate.Value.Date.ToShortDateString();

List<Reporte> Reportes = await Task.Run(() => 
    db_data.TraerReportes(Environment.MachineName, param));

您不需要任何其他更改,您不应该需要 Control.Invoke()
假设 TraerReportes 不执行 UI 工作。

关于c# - "The subprocess making the call can not access this object because the owner is another thread"异常异步/等待 WPF C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51092943/

相关文章:

C# WPF 图表工具包 : How to get independent-axis value from ColumnSeries in MouseRightButtonDown?

c# - Ajax AutoCompleteExtender OnClientPopulated 事件不会在 Firefox 中触发

c# - 在运行时将图像添加到 Crystal Report

c# - WPF 不活动和事件

c# - IdentityServer4 - 根据 client_id 使用不同的用户存储

c# - 在父类上调用静态方法时,父类可以推断出子类(C#)的类型吗?

c# - 以不同用户身份从 .NET 服务启动 .NET 应用程序时出现权限问题?

c# - 如何从包含 c#.net 中的 2 个元素的列表中单独获取第二个元素?

c# - 任务取消暂停 UI

c# - 如何为 WPF TreeView 设置垂直滚动条,而不是水平滚动条?