I make MVC simple game, but i got some troubles with multithreading.
initialization form with it's own thread:
private void InitForm()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
_form = new GameForm(UpdateWindow);
_form.ResizeEnd += FormOnResizeEnd;
_form.ResizeBegin += _form_ResizeBegin;
_formThread = new Thread(new ThreadStart(delegate
{
Application.Run(_form);
}));
_formThread.Start();
}
controller calls it ~60 times per second
private void Draw()
{
_gameField.Update(_bufferedGraphics.Graphics);
_gameObject.Update(_bufferedGraphics.Graphics);
_form.Invalidate();
}
On Invalidate() form calls
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
_update.Invoke(e.Graphics);
}
_update is a delegate, which do this:
public void UpdateWindow(Graphics graphics)
{
_bufferedGraphics.Render(graphics);
}
But sometimes i get System.InvalidOperationException in System.Drawing.dll (object in use elsewhere) on
_gameField.Update(_bufferedGraphics.Graphics);
_gameField.Update:
public void Update(Graphics graphics)
{
graphics.DrawImage(_gameField, 0, 0, _gameField.Width, _gameField.Height);
}
I understood that i cant Update _bufferedGraphics until _form.OnPaint...
What object must be locked?
How can i resolve this problem?
Thank you for answer.
Run form in the main thread