UserState Property
Collapse the table of content
Expand the table of content

AsyncCompletedEventArgs.UserState Property


Gets the unique identifier for the asynchronous task.

Namespace:   System.ComponentModel
Assembly:  System (in System.dll)

public object UserState { get; }

Property Value

Type: System.Object

An object reference that uniquely identifies the asynchronous task; otherwise, null if no value has been set.

If a class supports multiple asynchronous methods, or multiple invocations of a single method, you can determine which task raised the MethodNameCompleted event by checking the value of the UserState property. Your code will need track these tokens, known as task IDs, as their corresponding asynchronous tasks start and complete.

The value of this property is set during the original call to the asynchronous method that started the task.

The following code example demonstrates using an AsyncOperation to track the lifetime of asynchronous operations. This code example is part of a larger example provided for the System.ComponentModel.AsyncOperationManager class.

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;
        bool result = e.IsPrime;

        ListViewItem lvi = UpdateListViewItem(

        if (lvi != null)
            lvi.BackColor = Color.LightGray;
            lvi.Tag = null;

Universal Windows Platform
Available since 4.5
.NET Framework
Available since 2.0
Portable Class Library
Supported in: portable .NET platforms
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1
Return to top
© 2015 Microsoft