Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

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 have to 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 how to use UserState to track the lifetime of asynchronous operations. The local variable used to store the values tracked by UserState is named taskID in this example. This code example is part of a larger example provided for the System.ComponentModel.AsyncOperationManager class.


// Start GetPersons as an asynchronous process.
public void GetPersonsAsync
    (int itemsCount, string name, object taskId)
{
    AsyncOperation asyncOp;

    // First make sure this is not an attempt to start the 
    // same thread twice.  Multiple threads will access the
    // taskID Dictionary, so it must be locked to serialize
    // access.
    lock (this)
    {
        if (taskIDs.ContainsKey(taskId))
        {
            throw new ArgumentException
                ("Task ID already exists", "taskID");
        }

        // Create a new AsyncOperation object
        // and put it in the taskID Dictionary.
        asyncOp =
            AsyncOperationManager.CreateOperation(taskId);
        taskIDs[taskId] = asyncOp;
    }

    // Start the asynchronous process.
    // The following line is the least amount of code to do 
    // this.  It uses a lambda expression.  Following it is 
    // commented code showing an alternative method.

    new Thread(() =>
        { GetPersons(itemsCount, name, asyncOp); }).Start();

    // The alternative is to include two lines here and
    // define separately the method that they reference and
    // a class you can use to pass parameters to Thread.Start:

    //   Thread myThread = 
    //       new Thread(new ThreadStart(StartThread));
    //   myThread.Start(new ThreadStartParms 
    //       {.ItemsCount=itemsCount, 
    //        .Name=name, 
    //        .AsyncOp=asyncOp });

    //   void StartThread()
    //   {
    //      GetPersons(itemsCount, name, asyncOp);
    //   }

    //   public class ThreadStartParms)
    //   {
    //       public int ItemsCount { get; set; }
    //       public string Name { get; set; }
    //       public AsyncOp AsyncOperation { get; set; }
    //   }

}



// The worker process for data retrieval.  Simulates a 
// time-consuming operation by using Thread.Sleep.
public void GetPersons
    (int itemsCount, string Name, AsyncOperation asyncOperation)
{
    bool canceled = false;
    Exception exception = null;

    List<Person> personList = new List<Person>();

    for (int i = 1; i <= itemsCount || itemsCount == 0; i++)
    {
        string currentName = Name + i;
        personList.Add(new Person()
        {
            Name = currentName,
            Age = i,
            Birthday = DateTime.Today.AddYears(-i),
            Available = (i % 2 == 0)
        });
        // Delay 1 second for each person.
        Thread.Sleep(1000);

        // Report progress by using AsyncOperation to raise
        // the ProgressChanged event.
        int percentComplete = 0;
        try
        {
            percentComplete =
                Convert.ToInt32(i * 100 / itemsCount);
        }
        catch (Exception ex)
        {
            exception = ex;
            break;
        }

        GetPersonsProgressChangedEventArgs progressChangedEventArgs =
            new GetPersonsProgressChangedEventArgs(
                currentName,
                percentComplete,
                asyncOperation.UserSuppliedState);
        asyncOperation.Post(AsyncOpProgressReportHandler,
                            progressChangedEventArgs);

        if (GetPersonsCheckForCancellation
            (asyncOperation.UserSuppliedState))
        {
            canceled = true;
            break;
        }
    }

    // Report completion by raising the Completed event.
    GetPersonsCompletedEventArgs completedEventArgs =
        new GetPersonsCompletedEventArgs(
            personList,
            exception,
            canceled,
            asyncOperation.UserSuppliedState);

    asyncOperation.PostOperationCompleted
        (AsyncOpCompletedHandler, completedEventArgs);
}


Silverlight

Supported in: 5, 4, 3

Silverlight for Windows Phone

Supported in: Windows Phone OS 7.1, Windows Phone OS 7.0

XNA Framework

Supported in: Xbox 360, Windows Phone OS 7.0

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback

Community Additions

Show:
© 2014 Microsoft