Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Editing Text object while in a task seems to break stuff  (Read 7874 times)

0 Members and 1 Guest are viewing this topic.

Frog

  • Newbie
  • *
  • Posts: 2
    • View Profile
Editing Text object while in a task seems to break stuff
« on: February 04, 2022, 05:51:00 am »
heyo, i was getting really strange behavior from sfml text
after changing DisplayedString while in a task, one of many issues could occur:
  • System.AccessViolationException when drawing the text
  • System.AccessViolationException when trying to get its local/global bounds
  • crash but with no error
  • no crash but text is rendered with visual errors such as incorrect characters and or distorted characters
it seems like memory is getting corrupted somehow but im not exactly sure why
code:
using System;
using System.Threading;
using System.Threading.Tasks;
using SFML.Graphics;
using SFML.Window;

internal class Program {

        public static RenderWindow Window;

        public static void Main(string[] args) {
                Window = new RenderWindow(new VideoMode(640, 480), "Test");
                Window.SetFramerateLimit(60);

                var textHolder = new TextHolder();

                while (Window.IsOpen) {
                        Window.Clear();
                        Window.Draw(textHolder);
                        Window.Display();
                }
        }
}

internal class TextHolder : Drawable {

        private Text _text;

        public TextHolder() {
                _text = new Text("Initial String", new Font("arial.ttf"));

                Task.Run(() => {
                        Thread.Sleep(1000);
                        _text.DisplayedString = "ABCDEFGHIKLMNOPQRSTUVWXYZ";
                        Console.WriteLine(_text.GetLocalBounds().Width);
                });
        }

        public void Draw(RenderTarget target, RenderStates states) {
                target.Draw(_text);
        }
}
sorry if a missed anything
real frog

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11033
    • View Profile
    • development blog
    • Email
Re: Editing Text object while in a task seems to break stuff
« Reply #1 on: February 04, 2022, 09:39:20 am »
SFML isn't thread-safe, so you can't just spin up a separate thread/task without synchronizing the shared resource (i.e. _text).

Also, you'll need to hold on to your Font object, otherwise it might be prematurely disposed.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Frog

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: Editing Text object while in a task seems to break stuff
« Reply #2 on: February 04, 2022, 09:45:12 am »
aaah yeah that makes sense, ill look in to doing that
thanks for the quick reply!
real frog