Skip to main content
gamedev.net
🔒 Locked

[.net] Help creating threads

Started by homer_3 1 reply 750+ views
Original Post
homer_3
homer_3
Ok I don't see what I'm missing. I've been looking and some tutorials and can't seem to create a thread. I have this class for scrolling the map.

class MapScroller
    {
        const int X_INC = 20;
        const int Y_INC = 20;
        int dir = 1;

        public void scrollH(Sprite map, Player player, int len)
        {
            if (len < 0)
                dir = -1;
            else
                dir = 1;
            len = Math.Abs(len);

            for (int i = 0; i < len; i+=X_INC)
            {
                map.position.X += X_INC * dir;
                Thread.Sleep(TimeSpan.FromMilliseconds(500));
            }
        }

        public void scrollV(Sprite map, Player player, int len)
        {
            if (len < 0)
                dir = -1;
            else
                dir = 1;
            len = Math.Abs(len);

            for (int i = 0; i < len; i += Y_INC)
            {
                map.position.Y += Y_INC * dir;
                Thread.Sleep(TimeSpan.FromMilliseconds(500));
            }
        }
    }

Then I try to create a thread from it with

 MapScroller mapScroller = new MapScroller();
 ThreadStart tt = new ThreadStart(mapScroller.scrollH(curMap, player, 800));
 Thread   mapScrollerThread = new Thread(tt);

But mapScroller.scrollH(curMap, player, 800) has an error that says "method name expected". What am I missing?
SiCrane
SiCrane
mapScroller.scrollH(curMap, player, 800) calls the function right then and there. What you want is a ThreadStart delegate. One way to do that would be:
class ScrollH {  Sprite map;  Player player;  int len;  MapScroller scroller;  ScrollH(Sprite map, Player player, int len, MapScroller scroller) {    this.map = map;    this.player = player;    this.len = len;    this.scroller = scroller;  }  void Execute() {    scroller.scrollH(map, player, len);  }}ThreadStart tt = new ThreadStart(new ScrollH(curMap, player, 800, mapScroller).Execute);
Rynus_Rein
Rynus_Rein
SiCrane is right, the constructor of Thread requires a ParameterizedThreadStart or ThreadStart delegate (.NET equivalent of function pointers), you may want to read into them: http://en.wikipedia.org/wiki/Delegate_(.NET)

You can do funny stuff with inline delegates:
Thread thread = new Thread(new ThreadStart(delegate {    // do code here}));thread.Start();

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.