I have a timer that calls a method every 15 seconds and that method takes some time to finish.
I have converted it to async
as much as possible for me but it still freezes the UI for almost 1 sec when it runs and since it runs every 15 seconds, it becomes annoying.
Any idea how to make this async
method run completely off the grid?
This is the timer method:
public static DispatcherTimer UpdateList = new DispatcherTimer();
//GlobalVars.MainList = new List<string>(); //saved list from previous declaration
public MainFunction()
{
this.InitializeComponent();
UpdateList.Tick += UpdateList_Tick; ;
UpdateList.Interval = new TimeSpan(0, 0, 0, 0, 15000);
UpdateList.Start();
//...
}
private async void UpdateList_Tick(object sender, object e)
{
using (var client = new ImapClient())
{
using (var cancel = new CancellationTokenSource())
{
await client.ConnectAsync("imap.gmail.com", 993, true, cancel.Token);
client.AuthenticationMechanisms.Remove("XOAUTH");
await client.AuthenticateAsync("email.com", "mail12345", cancel.Token);
var inbox = client.Inbox;
await inbox.OpenAsync(FolderAccess.ReadOnly, cancel.Token);
// let's try searching for some messages...
DateTime date = DateTime.Now;
DateTime mondayOfLastWeek = date.AddDays(-(int)date.DayOfWeek - 6);
var query = SearchQuery.DeliveredAfter(mondayOfLastWeek)
.And(SearchQuery.SubjectContains("search"))
.And(SearchQuery.All);
List<string> newList = new List<string>();
foreach (var uid in inbox.Search(query, cancel.Token))
{
var message = inbox.GetMessage(uid, cancel.Token);
string trimmedMSGEmtyLines = Regex.Replace(message.TextBody, @"^\s+$[\r\n]*", "", RegexOptions.Multiline);
newList.Add(message.Date.LocalDateTime + Environment.NewLine + trimmedMSGEmtyLines);
}
await client.DisconnectAsync(true, cancel.Token);
if (!GlobalVars.MainList.SequenceEqual(newList))
{
GlobalVars.MainList = newList;
}
}
}
}
Update: MailKit, Portable.Text.Encoding, MimeKit