獲取異步任務的唯一標識符。
命名空間: System.ComponentModel
程序集: System(在 System.dll 中)
類型:System..::.Object
唯一標識異步任務的對象引用;如果未設置任何值,則爲 nullNothingnullptrnull 引用(在 Visual Basic 中爲 Nothing)。
備註
如果類支持多個異步方法或對單個方法的多次調用,則可以通過檢查 UserState 屬性的值確定哪個任務引發了 MethodNameCompleted 事件。當標記(稱爲任務 ID)對應的異步任務開始和完成時,您的代碼需要跟蹤這些標記。此屬性的值是在對啓動任務的異步方法進行初始調用時設置的。
示例
下面的代碼示例演示如何使用 AsyncOperation 來跟蹤異步操作的生存期。此代碼示例摘自一個爲
System.ComponentModel..::.AsyncOperationManager
類提供的更大的示例。
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
...
// This event handler updates the ListView control when the
// PrimeNumberCalculator raises the CalculatePrimeCompleted
// event. The ListView item is updated with the appropriate
// outcome of the calculation: Canceled, Error, or result.
private void primeNumberCalculator1_CalculatePrimeCompleted(
object sender,
CalculatePrimeCompletedEventArgs e)
{
Guid taskId = (Guid)e.UserState;
if (e.Cancelled)
{
string result = "Canceled";
ListViewItem lvi = UpdateListViewItem(taskId, result);
if (lvi != null)
{
lvi.BackColor = Color.Pink;
lvi.Tag = null;
}
}
else if (e.Error != null)
{
string result = "Error";
ListViewItem lvi = UpdateListViewItem(taskId, result);
if (lvi != null)
{
lvi.BackColor = Color.Red;
lvi.ForeColor = Color.White;
lvi.Tag = null;
}
}
else
{
bool result = e.IsPrime;
ListViewItem lvi = UpdateListViewItem(
taskId,
result,
e.FirstDivisor);
if (lvi != null)
{
lvi.BackColor = Color.LightGray;
lvi.Tag = null;
}
}
}
摘自MSDN:http://technet.microsoft.com/zh-cn/magazine/system.componentmodel.asynccompletedeventargs.userstate%28VS.90%29.aspx