use*_*584 4 .net c# asynchronous task winforms
我正在玩C#和Window Forms中的任务,我遇到了一个奇怪的效果.我有一个表格,其中包含一个每300毫秒勾选一次的计时器.tick事件将该表单中控件的背景更改为随机颜色.我有另一个按钮,点击它时会启动一个新的任务,它只是Thread.Sleep
用来等待3秒钟.我还插入了一个用于记录的文本框.
因为从我对任务的理解,他们没有创建新线程来运行任务(并且日志也显示了这一点),我希望第一个按钮在任务运行时停止改变它的颜色3秒,因为一个线程一次只能做一件事.按钮闪烁或3秒钟无效.
然而,这个假设似乎是错误的,因为即使在假设线程正在睡觉时按钮也会愉快地改变它的颜色!怎么会这样?
跟进:我注意到,从tasks方法中,我必须使用Invoke
访问日志记录文本框.但是,根据MSDN的Control.InvokeRequired文档:
如果控件的句柄是在与调用线程不同的线程上创建的,则为true (表示必须通过调用方法调用控件); 否则,错误.
既然这是单线程场景怎么可能InvokeRequired
是真的呢?
PS:我知道这Task.Delay
是件事.我想了解为什么UI线程在a期间不会阻塞Thread.Sleep
.
日志输出 ::
[T9] Before await
[T9] [I] Task Start
[T9] [I] Task End
[T9] After await
Run Code Online (Sandbox Code Playgroud)
闪烁按钮还显示了tick事件处理程序执行的线程的线程ID,它也是9.
完整代码:
using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AsyncAwaitTest
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public class Form1 : Form
{
private readonly Button _buttonFlash;
private readonly System.Windows.Forms.Timer _timerFlash;
private readonly TextBox _textLog;
private readonly Random _rand = new Random();
public Form1()
{
_buttonFlash = new Button();
var buttonAwait = new Button();
_timerFlash = new System.Windows.Forms.Timer();
_textLog = new TextBox();
SuspendLayout();
_buttonFlash.Location = new Point(12, 12);
_buttonFlash.Size = new Size(139, 61);
buttonAwait.Location = new Point(213, 12);
buttonAwait.Size = new Size(110, 61);
buttonAwait.Text = "Wait Some Time";
buttonAwait.Click += buttonAwait_Click;
_timerFlash.Interval = 300;
_timerFlash.Tick += TimerFlashTick;
_textLog.Location = new Point(36, 79);
_textLog.Multiline = true;
_textLog.Size = new Size(351, 167);
ClientSize = new Size(480, 286);
Controls.Add(_textLog);
Controls.Add(buttonAwait);
Controls.Add(_buttonFlash);
Text = "Form1";
ResumeLayout(false);
PerformLayout();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
_timerFlash.Start();
}
private void Log(string text)
{
if (InvokeRequired)
{
Invoke((Action<string>) Log, "[I] " + text);
return;
}
_textLog.Text += string.Format("[T{0}] {1}{2}", Thread.CurrentThread.ManagedThreadId, text, Environment.NewLine);
}
private void TimerFlashTick(object sender, EventArgs e)
{
_buttonFlash.Text = Thread.CurrentThread.ManagedThreadId.ToString();
_buttonFlash.BackColor = Color.FromArgb(255, _rand.Next(0, 255), _rand.Next(0, 255), _rand.Next(0, 255));
}
private async void buttonAwait_Click(object sender, EventArgs e)
{
Log("Before await");
await Task.Factory.StartNew(Something);
Log("After await");
}
private void Something()
{
Log("Task Start");
Thread.Sleep(3000);
Log("Task End");
}
}
}
Run Code Online (Sandbox Code Playgroud)
根据我对Tasks的理解,他们不会创建新的线程来运行任务
该任务不一定创建一个新的线程本身,而是Task.Factory.StartNew
做.它使用当前任务调度程序调度要执行的任务,该调度程序默认从线程池中提取工作线程.
请阅读:
http://msdn.microsoft.com/en-us/library/dd997402(v=vs.110).aspx