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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM