AsyncCompletedEventArgs
.
.
::
.UserState 属性
获取异步任务的唯一标识符。
命名空间: System.ComponentModel
程序集: System(在 System.dll 中)
类型:System..::.Object
唯一标识异步任务的对象引用;如果未设置任何值,则为 nullNothingnullptrnull 引用(在 Visual Basic 中为 Nothing)。
备注
如果类支持多个异步方法或对单个方法的多次调用,则可以通过检查
UserState 属性的值确定哪个任务引发了
MethodName
Completed 事件。当标记(称为任务 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