几天前我开始在 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();
}
我认为问题来自上层代码。在我的程序运行大约一分钟后抛出异常。这是一个例外:
mscorlib.dll 中出现“System.Reflection.TargetInvocationException”类型的未处理异常
附加信息:调用的目标已引发异常。
之后我收到这条消息:
当前位置没有可用的源代码。
我知道我的源代码有点难看,等我解决了这个问题,我会改进它。你能告诉我如何解决它吗?