Thread.Sleep() - для какого потока вызывается? - C#
Формулировка задачи:
Почему по вызову Thread.Sleep зависает основной поток,а не второстепенный?
/*
/*
* Сделано в SharpDevelop.
* Пользователь: User
* Дата: 28.01.2017
* Время: 18:00
*
* Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
*/
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace Game_Test
{
/// <summary>
/// Description of GameInterface.
/// </summary>
public partial class GameInterface : UserControl
{
Booxes box;
public bool flag = false;
public GameInterface()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
box = new Booxes(MainForm.MainPath);
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void GameInterfacePaint(object sender, PaintEventArgs e)
{
if(!flag)
{
flag = true;
DrawBooxes(e);
}
else
{
while(true)
{
DrawBooxes(e);
Thread.Sleep(10000);
}
}
}
void DrawBooxes(PaintEventArgs e)
{
int x = 0;
int y = 0;
for (int i = 0;i<500;i++)
{
for (int j = 0;j<500;j++)
{
e.Graphics.DrawImage(box.Box_Image,new Point(x,y));
y+=21;
}
x+=21;
y=0;
}
}
}
}/*
* Сделано в SharpDevelop.
* Пользователь: User
* Дата: 28.01.2017
* Время: 18:00
*
* Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
*/
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading;
namespace Game_Test
{
/// <summary>
/// Description of MainForm.
/// </summary>
///
class Inform
{
}
public partial class MainForm : Form
{
public const string MainPath = @"C:\Users\User\Documents\SharpDevelop Projects\Game_Test\Game_Test\Ресурсы\коробка.png";
GameInterface gameinterface;
Settings settings;
Thread gameplay;
bool flag = false;
public MainForm()
{
//
// The InitializeComponent() call is required for Windows Forms designer support.
//
InitializeComponent();
gameinterface = new GameInterface();
settings = new Settings();
this.Controls.Add(gameinterface);
this.AddOwnedForm(settings);
gameinterface.Invalidate();
//
// TODO: Add constructor code after the InitializeComponent() call.
//
}
void Button1Click(object sender, EventArgs e)
{
if (!flag)
{
try
{
flag = true;
gameplay = new Thread(gameinterface.Invalidate);
gameplay.Start();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
else
{
try
{
flag = !flag;
gameplay.Abort(); ///
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}
}
}
}Решение задачи: «Thread.Sleep() - для какого потока вызывается?»
textual
Листинг программы
class Game
{
public PointF Center { get; }
public float Radius { get; }
public float BallRadius { get; }
public float RevolvingFrequency { get; }
private double _timeElapsed;
private PointF BallCenter
{
get
{
double angle = RevolvingFrequency * _timeElapsed / 1000;
var ballCenter = new PointF((float)(Center.X + Radius * Math.Cos(angle)),
(float)(Center.Y + Radius * Math.Sin(angle)));
return ballCenter;
}
}
public event Action<bool> GameOver;
public void Click(float x, float y)
{
var ballCenter = BallCenter;
if (Math.Pow(x - ballCenter.X, 2) + Math.Pow(y - ballCenter.Y, 2) <= Math.Pow(BallRadius, 2))
GameOver?.Invoke(true);
else
GameOver?.Invoke(false);
}
public void Update(TimeSpan dt)
{
_timeElapsed += dt.TotalMilliseconds;
}
public void Draw(Graphics g)
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
var ballCenter = BallCenter;
g.FillEllipse(Brushes.Red, ballCenter.X - BallRadius, ballCenter.Y - BallRadius, 2 * BallRadius, 2 * BallRadius);
}
public Game(PointF center, float radius, float frequency, float ballRadius)
{
Center = center;
Radius = radius;
RevolvingFrequency = frequency;
BallRadius = ballRadius;
}
public void Restart()
{
_timeElapsed = 0;
}
}
class MainForm: Form
{
public MainForm()
{
DoubleBuffered = true;
Cursor = Cursors.NoMove2D;
Size = new Size(400, 400);
var game = new Game(new PointF(200, 200), 100, 3f, 20);
var lastUpdate = DateTime.Now;
var updater = new System.Windows.Forms.Timer();
game.GameOver += won =>
{
updater.Enabled = false;
if (won)
{
MessageBox.Show("You win!");
}
else
{
MessageBox.Show("You loose!");
}
game.Restart();
lastUpdate = DateTime.Now;
updater.Enabled = true;
};
Click += (s, a) =>
{
var args = a as MouseEventArgs;
game.Click(args.X, args.Y);
};
updater.Interval = 1;
updater.Tick += (s, a) =>
{
var now = DateTime.Now;
game.Update(now - lastUpdate);
lastUpdate = now;
Invalidate();
};
int count = 0;
Paint += (s, a) =>
{
game.Draw(a.Graphics);
};
updater.Enabled = true;
}
}