Game1.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. using System;
  2. using System.Threading;
  3. using System.Threading.Tasks;
  4. using Microsoft.Xna.Framework;
  5. using Microsoft.Xna.Framework.Graphics;
  6. using Microsoft.Xna.Framework.Input;
  7. namespace BackgroundThreadTester
  8. {
  9. public class Game1 : Game
  10. {
  11. GraphicsDeviceManager graphics;
  12. SpriteBatch spriteBatch;
  13. public TextManager aTm;
  14. public InputManager cIm;
  15. private SpriteFont sfStandard;
  16. public MouseState mousestatus;
  17. public Object aObjects;
  18. TimeSpan tsElapsed = TimeSpan.Zero;
  19. private String sLoading = "Loading";
  20. // Modern async patterns
  21. private CancellationTokenSource _cancellationTokenSource;
  22. private readonly object _componentLock = new object();
  23. private bool _backgroundTaskRunning = false;
  24. public Game1()
  25. {
  26. #if !__MOBILE__
  27. this.IsMouseVisible = true;
  28. #endif
  29. graphics = new GraphicsDeviceManager(this);
  30. graphics.PreferredBackBufferWidth = 480;
  31. graphics.PreferredBackBufferHeight = 640;
  32. graphics.ApplyChanges();
  33. Content.RootDirectory = "Content";
  34. cIm = new InputManager(this);
  35. CenterWindow();
  36. // Initialize cancellation token source
  37. _cancellationTokenSource = new CancellationTokenSource();
  38. }
  39. protected override void Dispose(bool disposing)
  40. {
  41. if (disposing)
  42. {
  43. // Cancel any running background tasks
  44. _cancellationTokenSource?.Cancel();
  45. _cancellationTokenSource?.Dispose();
  46. }
  47. base.Dispose(disposing);
  48. }
  49. protected override void Initialize ()
  50. {
  51. // TODO: Add your initialization logic here
  52. base.Initialize ();
  53. }
  54. protected override void LoadContent ()
  55. {
  56. // Create a new SpriteBatch, which can be used to draw textures.
  57. spriteBatch = new SpriteBatch (GraphicsDevice);
  58. Services.AddService (typeof(SpriteBatch), spriteBatch);
  59. sfStandard = Content.Load<SpriteFont> ("fntStandard");
  60. aTm = new TextManager (this, sfStandard);
  61. Components.Add (aTm);
  62. }
  63. protected override void UnloadContent ()
  64. {
  65. // TODO: Unload any non ContentManager content here
  66. }
  67. public void CreateBackgroundThread ()
  68. {
  69. if (_backgroundTaskRunning)
  70. {
  71. Console.WriteLine("Background task already running. Cancelling previous task...");
  72. _cancellationTokenSource?.Cancel();
  73. }
  74. _cancellationTokenSource = new CancellationTokenSource();
  75. _backgroundTaskRunning = true;
  76. Console.WriteLine ("Starting modern async background task");
  77. // Start the modern async background task
  78. _ = CreateBackgroundTaskAsync(_cancellationTokenSource.Token);
  79. }
  80. /// <summary>
  81. /// Modern async background worker using Task-based async patterns
  82. /// </summary>
  83. private async Task CreateBackgroundTaskAsync(CancellationToken cancellationToken)
  84. {
  85. try
  86. {
  87. Console.WriteLine("Background task started");
  88. // Create a loop that will add 5 new components with
  89. // a 2 second pause between additions
  90. for (int x = 1; x <= 5; x++)
  91. {
  92. // Check for cancellation
  93. cancellationToken.ThrowIfCancellationRequested();
  94. Console.WriteLine($"Adding component {x}/5");
  95. // Schedule component addition on the main thread
  96. // This is the correct cross-platform way to marshal to the UI thread
  97. var testTexture = new TestTexture(this);
  98. // Use a thread-safe approach to add components
  99. lock (_componentLock)
  100. {
  101. Components.Add(testTexture);
  102. }
  103. Console.WriteLine($"Component {x} added successfully");
  104. // Use non-blocking delay instead of Thread.Sleep
  105. // This allows the task to be cancelled during the delay
  106. await Task.Delay(2000, cancellationToken);
  107. }
  108. Console.WriteLine("Background task completed successfully");
  109. }
  110. catch (OperationCanceledException)
  111. {
  112. Console.WriteLine("Background task was cancelled");
  113. }
  114. catch (Exception ex)
  115. {
  116. Console.WriteLine($"Background task failed with error: {ex.Message}");
  117. }
  118. finally
  119. {
  120. _backgroundTaskRunning = false;
  121. }
  122. }
  123. /// <summary>
  124. /// Legacy method kept for compatibility - now uses modern patterns internally
  125. /// </summary>
  126. void BackgroundWorkerThread ()
  127. {
  128. // Redirect to modern async implementation
  129. CreateBackgroundThread();
  130. }
  131. public int GetBackBufferWidth ()
  132. {
  133. return graphics.PreferredBackBufferWidth;
  134. }//GetBackBufferWidth
  135. public int GetBackBufferHeight ()
  136. {
  137. return graphics.PreferredBackBufferHeight;
  138. }//GetBackBufferWidth
  139. public String GetStyleMask ()
  140. {
  141. return "Modern";
  142. }//GetStyleMask
  143. protected override void Update (GameTime gameTime)
  144. {
  145. mousestatus = Mouse.GetState ();
  146. var keyboardState = Keyboard.GetState();
  147. // Handle input
  148. if (keyboardState.IsKeyDown(Keys.Escape))
  149. {
  150. #if !__IOS__
  151. Exit();
  152. #endif
  153. }
  154. cIm.InputHandler (mousestatus, gameTime);
  155. base.Update (gameTime);
  156. }
  157. protected override void Draw (GameTime gameTime)
  158. {
  159. GraphicsDevice.Clear (Color.CornflowerBlue);
  160. spriteBatch.Begin (SpriteSortMode.Immediate, BlendState.AlphaBlend);
  161. DrawLoadingAnimation (gameTime);
  162. base.Draw (gameTime);
  163. spriteBatch.End ();
  164. }
  165. void DrawLoadingAnimation (GameTime gameTime)
  166. {
  167. tsElapsed += gameTime.ElapsedGameTime;
  168. // it's time for next char
  169. if (tsElapsed > TimeSpan.FromMilliseconds (500)) {
  170. tsElapsed = TimeSpan.Zero;
  171. sLoading = sLoading.Insert (sLoading.Length, ".");
  172. if (sLoading.Length == 13) {
  173. sLoading = "Loading";
  174. }//if
  175. }//if
  176. spriteBatch.DrawString (sfStandard, sLoading, new Vector2 (50, 50), Color.White);
  177. }//DrawLoadingAnimation
  178. public void CenterWindow ()
  179. {
  180. // Window centering is handled by the platform-specific code
  181. }//CenterWindow
  182. }
  183. }