How to assign Values to a Property of an object using Task in C#

2.4k views Asked by At

I'm Having a Model Class, each property is mapped with a Model Class.

Consider the Model Class "Contact"

public class Contact
{
    public Profile profileInfo { get; set; }
    public bool isActive { get; set; }
}

public class Profile
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Task related C# Code is

public void MapContact(ref Contact contactInfo)    
{
    List<Task> taskList = new List<Task>();

    taskList.Add(Task.Factory.StartNew(() =>
    {
        contactInfo.profileInfo = client.GetProfileInfo(1);
    }));

    Task.WaitAll(taskList.ToArray());
}

I'm getting the Compile Time error "Cannot use ref or out parameter 'contactInfo' inside an anonymous method, lambda expression, or query expression" in the following statement

contactInfo.profileInfo = client.GetProfileInfo(1);

Kindly assist me how to use Task efficiently without any Compile-Time Error.

Here with I attached the Screenshot

enter image description here

1

There are 1 answers

4
AudioBubble On BEST ANSWER

Just declare a local variable of same type Contact and just pass this local variable to that Task

C# Code:

public void MapContact(ref Contact contactInfo)
{
    List<Task> taskList = new List<Task>();

    Contact pro = contactInfo;

    taskList.Add(Task.Factory.StartNew(() => 
        { pro.profileInfo = new Profile() 
            { 
                FirstName = "Stack", 
                LastName = "Overflow" 
            }; 
        }));

    Task.WaitAll(taskList.ToArray());
}

The LinqPad Output is enter image description here