Skip to content

Simple function to replace complicated Threads?

Adam Turner

Asked Jul 12, 2007, 12:48 PM EDT2 answers
Share
LinkedInX
Hello, I'm trying to figure out a nice way to create a simple spawn() function for a simple game engine I'm working on to make it easier to use Threads. I'm unfamiliar with events but I'm thinking that may be what I need to get rid of the while statement below. I'd like any help I can get as I'm fairly new to programming in anything other than BYOND.

My code:
C#
public delegate void function2call();
public void spawn(int time2sleep, function2call _function, ref bool isdone)
{
if (_function == null) return;
Thread gamethread = new Thread(new ThreadStart(_function));
sleep(time2sleep);
gamethread.Start();
while (!isdone) ;
gamethread.Join();
}

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0
    Yes,

    You probably don't want the while statement below otherwise you are stuck in the spawn method.    If you want to know when the thread is done, you should probably use  a different model, the delegate/BeginInvoke method.  This way you can pass a callback into the thread that gets called once your thread is finished.
    0
  • 0
    Thanks for your help and the article, but I'm still fuzzy on this issue (after trying for 5 hours until 3 in the morning hehe).

    I've reworked the code into what I have below but I haven't tested it and I wouldn't be surprised if it does nothing more than throw an exception of some variety. Any suggestions?


    public delegate T FunctionPointer<T>();

    public void spawn(int time2sleep, FunctionPointer<object> _function) //retrieve

    {

    if (_function == null) return;

    sleep(time2sleep);

    _function.BeginInvoke(endspawn, _function);

    }

    private void endspawn(IAsyncResult result)

    {

    FunctionPointer<object> _function = result.AsyncState as FunctionPointer<object>;

    _function.EndInvoke(result);

    }

    0