วิธีทำการดำเนินการ IMAP แบบอะซิงโครนัสบนอีเมล
การดำเนินการแบบอะซิงโครนัสกับ ImapClient
การทำงานกับข้อความสามารถทำได้แบบอะซิงโครนัสด้วยการใช้ Aspose.Email ImapClient. บทความนี้แสดงการดึงข้อความจากกล่องจดหมายแบบอะซิงโครนัส และแสดงวิธีแสดงรายการข้อความโดยกำหนดเงื่อนไขการค้นหาโดยใช้ MailQuery. จะมีการแสดงแยกต่างหากว่าจะแทรกการดำเนินการของข้อความอีเมลที่เริ่มด้วยรูปแบบอะซิงโครนัสแบบ task-based (TAP) เมธอด.
ดึงข้อความแบบอะซิงโครนัส
โค้ดตัวอย่างต่อไปนี้แสดงวิธีการดึงข้อความแบบอะซิงโครนัส.
List Messages Asynchronously with MailQuery
นี้ MailQuery คลาสสามารถใช้ระบุเงื่อนไขการค้นหาเพื่อดึงรายการข้อความที่ระบุแบบอะซิงโครนัส ตามที่แสดงในตัวอย่างโค้ดต่อไปนี้
ส่งข้อความแบบไม่ประสานงาน
การส่งอีเมลแบบอะซิงโครนัสเป็นสิ่งที่สะดวกมาก เพราะกระบวนการนี้ไม่บล็อกการทำงานของโปรแกรมหรือเธรด แทนที่จะรอให้อีเมลส่งเสร็จก่อนทำงานอื่น โปรแกรมสามารถทำงานต่อได้ขณะอีเมลกำลังส่งในพื้นหลัง
คุณสมบัติดังต่อไปนี้จะช่วยคุณทำการส่งแบบอะซิงโครนัสในโปรเจกต์ของคุณ:
-
IAsyncImapClient - อนุญาตให้แอปพลิเคชันเข้าถึงและจัดการข้อความโดยใช้โปรโตคอล IMAP (Internet Message Access Protocol).
-
ImapClient.CreateAsync - สร้างอินสแตนซ์ใหม่ของคลาส Aspose.Email.Clients.Imap.ImapClient
ตัวอย่างโค้ดด้านล่างนี้แสดงวิธีแสดงรายการข้อความในพื้นหลัง:
// Authenticate the client to obtain necessary permissions
static readonly string tenantId = "YOU_TENANT_ID";
static readonly string clientId = "YOU_CLIENT_ID";
static readonly string redirectUri = "http://localhost";
static readonly string username = "username";
static readonly string[] scopes = { "https://outlook.office.com/IMAP.AccessAsUser.All" };
// Use the ImapAsync method for asynchronous operations
static async Task Main(string[] args)
{
await ImapAsync();
Console.ReadLine();
}
// Establish the connection with the server
// Create an instance of the ImapClient asynchronously using the CreateAsync method
// Select the Inbox folder using SelectFolderAsync method to complete and fetch the list of email messages asynchronously using the ListMessagesAsync method.
static async Task ImapAsync()
{
var tokenProvider = new TokenProvider(clientId, tenantId, redirectUri, scopes);
var client = ImapClient.CreateAsync("outlook.office365.com", username, tokenProvider, 993).GetAwaiter().GetResult();
await client.SelectFolderAsync(ImapFolderInfo.InBox);
var messages = await client.ListMessagesAsync();
Console.WriteLine("Messages :" + messages.Count);
}
// Token provider implementation
public class TokenProvider : IAsyncTokenProvider
{
private readonly PublicClientApplicationOptions _pcaOptions;
private readonly string[] _scopes;
public TokenProvider(string clientId, string tenantId, string redirectUri, string[] scopes)
{
_pcaOptions = new PublicClientApplicationOptions
{
ClientId = clientId,
TenantId = tenantId,
RedirectUri = redirectUri
};
_scopes = scopes;
}
public async Task<OAuthToken> GetAccessTokenAsync(bool ignoreExistingToken = false, CancellationToken cancellationToken = default)
{
var pca = PublicClientApplicationBuilder
.CreateWithApplicationOptions(_pcaOptions).Build();
try
{
var result = await pca.AcquireTokenInteractive(_scopes)
.WithUseEmbeddedWebView(false)
.ExecuteAsync(cancellationToken);
return new OAuthToken(result.AccessToken);
}
catch (MsalException ex)
{
Console.WriteLine($"Error acquiring access token: {ex}");
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex}");
}
return null;
}
public void Dispose()
{
}
}
การจัดการการดำเนินการแบบอะซิงโครนัส
ขัดจังหวะเมธอด TAP
ตั้งแต่ .NET Framework 4.5 เป็นต้นไป คุณสามารถใช้เมธอดแบบอะซิงโครนัสที่ทำตามโมเดล TAP ตัวอย่างโค้ดด้านล่างแสดงวิธีเพิ่มหลายข้อความโดยใช้เมธอดแบบ task-based asynchronous pattern ที่ชื่อ AppendMessagesAsync และจากนั้นขัดจังหวะกระบวนการนี้หลังจากสักครู่.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
List<MailMessage> mailMessages = new List<MailMessage>();
// create mail messages
for (int i = 0; i < 100; i++)
mailMessages.Add(new MailMessage(senderEmail, receiverEmail, $"Message #{i}", "Text"));
using (ImapClient client = new ImapClient(host, 993, senderEmail, password, SecurityOptions.SSLImplicit))
{
CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
Exception exception = null;
ThreadPool.QueueUserWorkItem(delegate
{
try
{
// start uploading the messages
var task = client.AppendMessagesAsync(mailMessages, cancellationTokenSource.Token);
AppendMessagesResult appendMessagesResult = task.GetAwaiter().GetResult();
Console.WriteLine("All messages have been appended.");
}
catch (Exception e)
{
exception = e;
}
finally
{
autoResetEvent.Set();
}
});
Thread.Sleep(5000);
// stop uploading the messages
cancellationTokenSource.Cancel();
autoResetEvent.WaitOne();
foreach (MailMessage mailMessage in mailMessages)
mailMessage.Dispose();
if (exception is OperationCanceledException)
Console.WriteLine("Operation has been interrupted: " + exception.Message);
}
ยกเลิกการดำเนินการแบบอะซิงโครนัส
บางครั้งคุณอาจต้องหยุดการดำเนินการแบบอะซิงโครนัส เพื่อจุดประสงค์นี้ไลบรารีของเรามีการยกเลิกการดำเนินการแบบอะซิงโครนัสผ่านพารามิเตอร์ CancellationToken เมื่อเรียกเมธอดอะซิงโครนัสที่รองรับการยกเลิก คุณสามารถส่งอินสแตนซ์ของ CancellationToken เป็นพารามิเตอร์ได้ CancellationToken ใช้เพื่อสัญญาณและควบคุมการยกเลิกการดำเนินการ
เพื่อเปิดใช้งานการยกเลิก คุณต้องสร้างอินสแตนซ์ของ CancellationTokenSource ที่ให้ CancellationToken ก่อน จากนั้นส่ง CancellationToken ไปยังเมธอดอะซิงโครนัส เพื่อให้เมธอดตรวจสอบคำขอยกเลิกระหว่างการทำงาน
นี่คือตัวอย่างที่แสดงการยกเลิกโดยใช้ CancellationToken:
CancellationTokenSource tokenSource = new CancellationTokenSource();
AppendMessagesResult appendMessagesResult = null;
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
ThreadPool.QueueUserWorkItem(delegate(object state)
{
try
{
appendMessagesResult = imapClient.AppendMessagesAsync(mmList, tokenSource.Token).GetAwaiter().GetResult();
}
catch (Exception ex)
{
}
finally
{
autoResetEvent.Set();
}
});
tokenSource.Cancel();
autoResetEvent.WaitOne();