Winform异步进程cpu增加到50%

时间:2013-10-05 00:36:28

标签: c# winforms asynchronous task-parallel-library async-await

我有以下代码:

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%< / strong>在我的申请流程中使用并长时间停留在那里。

我确定异步方法有问题,可能是在尝试将照片图像设置为异步控制时。

有人可以指导我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

试试这个。

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();
            Thread.Sleep(200);
        }
     }
     catch
     {
        return result;
     }
  }