Thread.Sleep() - для какого потока вызывается? - C#

Узнай цену своей работы

Формулировка задачи:

Почему по вызову Thread.Sleep зависает основной поток,а не второстепенный?
Листинг программы
  1. /*
  2. /*
  3. * Сделано в SharpDevelop.
  4. * Пользователь: User
  5. * Дата: 28.01.2017
  6. * Время: 18:00
  7. *
  8. * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
  9. */
  10. using System;
  11. using System.ComponentModel;
  12. using System.Drawing;
  13. using System.Windows.Forms;
  14. using System.Threading;
  15. namespace Game_Test
  16. {
  17. /// <summary>
  18. /// Description of GameInterface.
  19. /// </summary>
  20. public partial class GameInterface : UserControl
  21. {
  22. Booxes box;
  23. public bool flag = false;
  24. public GameInterface()
  25. {
  26. //
  27. // The InitializeComponent() call is required for Windows Forms designer support.
  28. //
  29. InitializeComponent();
  30. box = new Booxes(MainForm.MainPath);
  31. //
  32. // TODO: Add constructor code after the InitializeComponent() call.
  33. //
  34. }
  35. void GameInterfacePaint(object sender, PaintEventArgs e)
  36. {
  37. if(!flag)
  38. {
  39. flag = true;
  40. DrawBooxes(e);
  41. }
  42. else
  43. {
  44. while(true)
  45. {
  46. DrawBooxes(e);
  47. Thread.Sleep(10000);
  48. }
  49. }
  50. }
  51. void DrawBooxes(PaintEventArgs e)
  52. {
  53. int x = 0;
  54. int y = 0;
  55. for (int i = 0;i<500;i++)
  56. {
  57. for (int j = 0;j<500;j++)
  58. {
  59. e.Graphics.DrawImage(box.Box_Image,new Point(x,y));
  60. y+=21;
  61. }
  62. x+=21;
  63. y=0;
  64. }
  65. }
  66.  
  67. }
  68. }
Листинг программы
  1. /*
  2. * Сделано в SharpDevelop.
  3. * Пользователь: User
  4. * Дата: 28.01.2017
  5. * Время: 18:00
  6. *
  7. * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
  8. */
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Drawing;
  12. using System.Windows.Forms;
  13. using System.Threading;
  14. namespace Game_Test
  15. {
  16. /// <summary>
  17. /// Description of MainForm.
  18. /// </summary>
  19. ///
  20. class Inform
  21. {
  22. }
  23. public partial class MainForm : Form
  24. {
  25. public const string MainPath = @"C:\Users\User\Documents\SharpDevelop Projects\Game_Test\Game_Test\Ресурсы\коробка.png";
  26. GameInterface gameinterface;
  27. Settings settings;
  28. Thread gameplay;
  29. bool flag = false;
  30. public MainForm()
  31. {
  32. //
  33. // The InitializeComponent() call is required for Windows Forms designer support.
  34. //
  35. InitializeComponent();
  36. gameinterface = new GameInterface();
  37. settings = new Settings();
  38. this.Controls.Add(gameinterface);
  39. this.AddOwnedForm(settings);
  40. gameinterface.Invalidate();
  41. //
  42. // TODO: Add constructor code after the InitializeComponent() call.
  43. //
  44. }
  45. void Button1Click(object sender, EventArgs e)
  46. {
  47. if (!flag)
  48. {
  49. try
  50. {
  51. flag = true;
  52. gameplay = new Thread(gameinterface.Invalidate);
  53. gameplay.Start();
  54. }
  55. catch(Exception ex)
  56. {
  57. MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
  58. }
  59. }
  60. else
  61. {
  62. try
  63. {
  64. flag = !flag;
  65. gameplay.Abort(); ///
  66. }
  67. catch(Exception ex)
  68. {
  69. MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
  70. }
  71. }
  72. }
  73. }
  74. }

Решение задачи: «Thread.Sleep() - для какого потока вызывается?»

textual
Листинг программы
  1. class Game
  2. {
  3.     public PointF Center { get; }
  4.     public float Radius { get; }
  5.     public float BallRadius { get; }
  6.     public float RevolvingFrequency { get; }
  7.     private double _timeElapsed;
  8.  
  9.     private PointF BallCenter
  10.     {
  11.         get
  12.         {
  13.             double angle = RevolvingFrequency * _timeElapsed / 1000;
  14.             var ballCenter = new PointF((float)(Center.X + Radius * Math.Cos(angle)),
  15.                 (float)(Center.Y + Radius * Math.Sin(angle)));
  16.             return ballCenter;
  17.         }
  18.     }
  19.    
  20.     public event Action<bool> GameOver;
  21.    
  22.     public void Click(float x, float y)
  23.     {
  24.         var ballCenter = BallCenter;
  25.         if (Math.Pow(x - ballCenter.X, 2) + Math.Pow(y - ballCenter.Y, 2) <= Math.Pow(BallRadius, 2))
  26.             GameOver?.Invoke(true);
  27.         else
  28.             GameOver?.Invoke(false);   
  29.     }
  30.    
  31.     public void Update(TimeSpan dt)
  32.     {
  33.         _timeElapsed += dt.TotalMilliseconds;
  34.     }
  35.    
  36.     public void Draw(Graphics g)
  37.     {
  38.         g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
  39.         var ballCenter = BallCenter;
  40.         g.FillEllipse(Brushes.Red, ballCenter.X - BallRadius, ballCenter.Y - BallRadius, 2 * BallRadius, 2 * BallRadius);
  41.     }
  42.    
  43.     public Game(PointF center, float radius, float frequency, float ballRadius)
  44.     {
  45.         Center = center;
  46.         Radius = radius;
  47.         RevolvingFrequency = frequency;
  48.         BallRadius = ballRadius;
  49.     }
  50.    
  51.     public void Restart()
  52.     {
  53.         _timeElapsed = 0;
  54.     }
  55. }
  56.  
  57. class MainForm: Form
  58. {
  59.     public MainForm()
  60.     {
  61.         DoubleBuffered = true;
  62.        
  63.         Cursor = Cursors.NoMove2D;
  64.        
  65.         Size = new Size(400, 400);
  66.        
  67.         var game = new Game(new PointF(200, 200), 100, 3f, 20);
  68.         var lastUpdate = DateTime.Now;
  69.  
  70.         var updater = new System.Windows.Forms.Timer();
  71.  
  72.         game.GameOver += won =>
  73.         {
  74.             updater.Enabled = false;
  75.             if (won)
  76.             {
  77.                 MessageBox.Show("You win!");
  78.             }
  79.             else
  80.             {
  81.                 MessageBox.Show("You loose!");
  82.             }
  83.             game.Restart();
  84.             lastUpdate = DateTime.Now;
  85.             updater.Enabled = true;
  86.         };
  87.  
  88.         Click += (s, a) =>
  89.         {
  90.             var args = a as MouseEventArgs;
  91.             game.Click(args.X, args.Y);
  92.         };
  93.    
  94.         updater.Interval = 1;
  95.         updater.Tick += (s, a) =>
  96.         {
  97.             var now = DateTime.Now;
  98.             game.Update(now - lastUpdate);
  99.             lastUpdate = now;
  100.             Invalidate();
  101.         };
  102.  
  103.         int count = 0;
  104.  
  105.         Paint += (s, a) =>
  106.         {
  107.             game.Draw(a.Graphics);
  108.         };
  109.        
  110.         updater.Enabled = true;
  111.     }
  112. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 3.933 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут