Winform的异步过程CPU提高到50% [英] Winform async process cpu increases to 50%

查看:238
本文介绍了Winform的异步过程CPU提高到50%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

private async void txtFirstName_TextChanged(object sender, EventArgs e)
{
            _keyStrokeTime = DateTime.Now;

            await KeyPressEvent();
}

在TextChanged事件我运行一个异步任务,将有去调用存储过程来查找匹配,然后返回姓名匹配的数量。

On textchanged event I run an async task that will have to go and call a stored procedure to find matches and then return the number of firstname matches.

下面是异步工作方式:

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控制code是:

The CustomControl.PersonResult control code is:

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");
                }


            });
        }
    }

似乎一切都正常工作时,我只是在文本框中键入一个字母,但如果我继续打字,也许6个字母,我可以看到我的 CPU将几乎50%〜90%<在我的应用程序的使用/ strong>并在那里停留很长一段时间。

Everything seems to work fine when I just type one letter in the TextBox, but if I keep typing maybe 6 letters I can see my CPU going to almost 50% to 90% of usage on my application process and stays there long time.

我敢肯定有一些错误的异步方法,试图设置异步照片图像的CustomControl。

Im sure there is something wrong on the async methods, maybe when trying to set async the photo image to the CustomControl.

有人能指导我如何解决这一问题?

Can someone guide me on how to fix this?

推荐答案

试试这个。

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;
     }
  }

这篇关于Winform的异步过程CPU提高到50%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆