WPF实现多线程加载数据

背景:最近自己用WPF做了一个邮件接收和发送系统,在获取邮件列表的时候整个界面会卡主,所以想办法解决这个问题。

演示:

test

实现代码:

这是写在ViewModel里的一个方法,用于获取邮件列表。ViewModel并没有Dispatcher,这是使用App.Current.Dispatcher去获取到UI的线程。

public void FetchAllMessages2(object paraNumber)
        {
            string num = paraNumber.ToString();
            string hostname = MailAccount.hostname;
            int port = MailAccount.port;
            bool useSsl = MailAccount.useSsl;
            string username = MailAccount.username;
            string password = MailAccount.password;
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List<Message> allMessages = new List<Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number
                int number = 20;
                if (!string.IsNullOrEmpty(num))
                {
                    try
                    {
                        number = Int32.Parse(num);
                    }
                    catch (Exception e)
                    {
                        System.Windows.MessageBox.Show(e.Message);
                    }
                }
                for (int i = messageCount; i > messageCount - number; i--)
                {
                    allMessages.Add(client.GetMessage(i));

                }

                // Now return the fetched messages
                List<Mail> maillist = new List<Mail>();
                maillist = ChangeMessageToMail(allMessages);
                App.Current.Dispatcher.BeginInvoke((Action)delegate()
                {
                    MailList = maillist;
                });
            }
        }
public MailViewModel()
        {
            //写下面这语句时会报“的重载均与委托‘System.Threading.ParameterizedThreadStart’不匹配”,后来把函数
            //FetchAllMessages2的变量改成Object类型就可以了
            Thread newThread = new Thread(new ParameterizedThreadStart(FetchAllMessages2));
            newThread.Start("15");
        }
posted @ 2017-05-03 13:13  Paddy138  阅读(1865)  评论(0编辑  收藏  举报