Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Microsoft.Xna.Framework;
- using System;
- using System.Collections.Generic;
- using System.Threading;
- namespace TestGame
- {
- public sealed class Npc
- {
- // FIFO collection for storing tasks.
- public Queue<KeyValuePair<NpcTasks, object[]>> Tasks;
- private Vector2[] path;
- private bool stopThread;
- private Thread thread; // Task update thread
- public Npc()
- {
- Tasks = new Queue<KeyValuePair<NpcTasks, object[]>>();
- path = new Vector2[0];
- InitThread();
- }
- public void Load()
- {
- if (thread.ThreadState == ThreadState.Running) throw new InvalidOperationException();
- if (thread.ThreadState != ThreadState.Unstarted) InitThread();
- thread.Start();
- }
- public void UnLoad()
- {
- stopThread = true; // Request a thread stop
- }
- public void Update()
- {
- // gamelogic update
- }
- private void InitThread()
- {
- // Set thread to its function
- thread = new Thread(RunThread);
- }
- private void RunThread()
- {
- // message loop
- while (!stopThread)
- {
- if (Tasks.Count > 0) TickThread(); // tick when task is available
- else Thread.Sleep(100); // do nothing for 100 ms
- }
- }
- private void TickThread()
- {
- KeyValuePair<NpcTasks, object[]> task = Tasks.Dequeue(); // get current task.
- switch (task.Key)
- {
- case NpcTasks.Walk:
- lock(path) // lock path to prevent interthread exceptions
- {
- path = new Vector2[] { Vector2.Zero, Vector2.One };
- }
- break;
- }
- }
- }
- public enum NpcTasks
- {
- Walk
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement