0
我已經看到關於同一主題的問題,但無法弄清楚如何解決這個問題。在我的遊戲中,我使用兩個線程Logic
線程和UI
線程。這是我遇到的問題C#System.InvalidOperationException:對象當前正在其他地方使用
System.InvalidOperationException: Object is currently in use elsewhere.
at System.Drawing.Graphics.FromImage(Image image)
at GECS.Core.Game.UpdateLoop() in c:\Us....ore\Game.cs:line 82
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
我只在UI線程上渲染。這是我的渲染循環。我把它放在構造函數中。
while (true) {
if (!Created) {
break;
}
if (Win32.PeekMessage(out msg, IntPtr.Zero, 0, 0, (uint)Win32.PM.REMOVE)) {
if (msg.message == (uint)Win32.WindowsMessage.WM_QUIT) {
break;
} else {
Win32.TranslateMessage(ref msg);
Win32.DispatchMessage(ref msg);
}
} else {
Text = Global.TITLE;
now = GetCurrentTime();
Graphics front = Graphics.FromHwnd(Handle);
front.DrawImage(backBuffer, 0, 0);
front.Dispose();
}
}
而我的邏輯
while (Created) {
now = GetCurrentTime();
while (now > game_time) {
elapsedTime = 1000/Global.ACTUAL_STEPS_FOR_SECOND;
Update(elapsedTime);
Map.UpdateObjects(elapsedTime);
game_time += step_size;
}
Graphics g = Graphics.FromImage(backBuffer); // This line is error
g.Clear(Color.WhiteSmoke);
Render(g);
g.Dispose();
}
環路我怎樣才能解決這個問題?已經嘗試在渲染循環之上粘貼邏輯循環,這使得我的遊戲非常慢。
謝謝
謝謝。有效。獲得24-35 fps。 –