gpt4 book ai didi

c# - C#多线程- 'System.Reflection.TargetInvocationException'

转载 作者:行者123 更新时间:2023-12-03 12:53:06 25 4
gpt4 key购买 nike

几天前,我开始使用C#(WPF)进行多线程编程,这是一个我无法解决的问题...我正在使用以下代码:

    void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
Random foodPosition = new Random();
double x,y;
Size size = new Size(30,30);
bool foodCreated = false;
Ellipse food = null;
Food foodObject = null;
Thread foodThread = new Thread(new ThreadStart(() =>
{
field.Dispatcher.Invoke(new Action(() =>
{
food = new Ellipse();
food.Fill = GenerateColor();
food.Width = size.Width;
food.Height = size.Height;
x = foodPosition.Next(0, (int)(playGroundSize.Width - size.Width) + 1);
y = foodPosition.Next(0, (int)(playGroundSize.Height - size.Height) + 1);
if (IsFree(x, y, size, 0))
{
playField.Children.Add(food);
Canvas.SetTop(food, y);
Canvas.SetLeft(food, x);

foodObject = new Food(food, new Point(x, y));
foodCollection.Add(foodObject,0);
foodCreated = true;
}
}));

if (foodCreated)
{
for (int i = 0; i < foodAliveTime; i++)
{
Thread.Sleep(1000);
foodCollection[foodObject]++;
}
field.Dispatcher.Invoke(new Action(() =>
{
playField.Children.Remove(foodObject.FoodObject);
//threadList[foodObject].Abort();
}));
}

}));
foodThread.Start();
}

我认为问题出在上层代码。在我的程序经过大约一分钟的工作后,引发了异常。这是异常(exception):

An unhandled exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll

Additional information: Exception has been thrown by the target of an invocation.



之后,我收到此消息:

There is no source code available for the current location.



我知道我的源代码有点丑陋,在解决这个问题后,我将使其变得更好。您能告诉我如何解决吗?

最佳答案

我想这个问题是对的:

field.Dispatcher.Invoke

您应该将这部分代码放入try/catch块中并进行捕获
TargetInvocationException

此异常可以提供有关问题所在的更多信息(请注意其 InnerException)。

P.S.
将整个函数放入try/catch块中;并不仅捕获 TargetInvocationException,还捕获至少 System.Exception

关于c# - C#多线程- 'System.Reflection.TargetInvocationException',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4528337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com