我有以下代码:
private async void txtFirstName_TextChanged(object sender, EventArgs e)
{
_keyStrokeTime = DateTime.Now;
await KeyPressEvent();
}
在 textchanged 事件上,我运行一个异步任务,该任务必须调用存储过程来查找匹配项,然后返回名字匹配项的数量。
这是异步任务方法:
CancellationTokenSource source;
private async Task KeyPressEvent()
{
if(source != null)
source.Cancel(); // this communicates to your task running on another thread to cancel
source = new CancellationTokenSource();
var results = await Task.Run<object>(() => SqlSearch(source.Token));
if (results != null)
{
this.Invoke(new Action(() =>
{
pnlTiles.Controls.Clear();
CustomControl.PersonResult newPersonTile = null;
for (int index = 0; index < (int)results; index++)
{
newPersonTile = new CustomControl.PersonResult(index.ToString(), index.ToString());
pnlTiles.Controls.Add(newPersonTile );
}
}));
}
}
private object SqlSearch(CancellationToken token)
{
Random random = new Random();
object result = 1;
try
{
bool done= false;
while (true )
{
if(!done)
{
// random numbers to simulate number of results
result = random.Next(1, 13);
done = true;
}
token.ThrowIfCancellationRequested();
}
}
catch
{
return result;
}
}
CustomControl.PersonResult 控件代码为:
public partial class PersonResult : UserControl
{
private string _name = string.Empty;
private string _lastName = string.Empty;
public PersonResult()
: this("name", "last name")
{
}
public PersonResult(string name,string lastName)
{
InitializeComponent();
_name = name;
_lastName = lastName;
}
protected override void InitLayout()
{
// load photo
GetPictureAsync();
base.InitLayout();
}
/// <summary>
///
/// </summary>
private void GetPictureAsync()
{
// This line needs to happen on the UI thread...
// TaskScheduler uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.StartNew(() =>
{
System.Threading.Thread.Sleep(3000);
if (this.pbPhoto.InvokeRequired)
{
this.pbPhoto.BeginInvoke(new Action(() =>
{
this.pbPhoto.Image = Utility.Common.GetResourceImage("woman_sample.jpg");
}));
}
else
{
this.pbPhoto.Image = Utility.Common.GetResourceImage("woman_sample.jpg");
}
});
}
}
当我只在TextBox中输入一个字母时,一切似乎都运行良好,但如果我继续输入大概 6 个字母,我可以看到我的CPU 在我的应用程序进程中几乎达到 50% 到 90%的使用率并在那里停留很长时间。
我确定异步方法有问题,可能是在尝试将照片图像异步设置到 CustomControl 时。
有人可以指导我如何解决这个问题吗?