0

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

Alexander
  • 9
  • 2
  • accessing visual components (any class with windows visual handle) is allowed only from main thread .... so in case you are accessing it in different thread weird things will start to happen. Like occasional random crash in unrelated winapi calls (even in different threads). – Spektre Nov 18 '17 at 16:55
  • Possible duplicate of [How do I update the GUI from another thread in C#?](https://stackoverflow.com/questions/661561/how-do-i-update-the-gui-from-another-thread-in-c) – Peter Bons Nov 18 '17 at 17:44
  • Oh, thank you, Spektre, you were right. I make my form in the main thread and it works well. I didnt know that fact :D – Alexander Nov 18 '17 at 21:00

0 Answers0