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#
publicdelegatevoidfunction2call();
publicvoidspawn(int time2sleep, function2call _function, refbool 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.
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.
Adam Turner55 pointsPosted Jul 12, 2007, 10:54 PM EDT
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>;
Mike GoldRank #50 · 30.6K pointsPosted Jul 12, 2007, 8:14 PM EDT
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.
Adam Turner55 pointsPosted Jul 12, 2007, 10:54 PM EDT
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);
}