我有这个代码:
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/