C# Why one should use TaskCompletionSource with Thread class

T.Zacks 3,991 Reputation points
2022-02-21T18:28:12.407+00:00

see the code

    public static Task<T> StartSTATask<T>(Func<T> func)
     {
         var tcs = new TaskCompletionSource<T>();
         Thread thread = new Thread(() =>
         {
             try
             {
                 tcs.SetResult(func());
             }
             catch (Exception e)
             {
                 tcs.SetException(e);
             }
         });
         thread.SetApartmentState(ApartmentState.STA);
         thread.Start();
         return tcs.Task;
     }

1) what is the meaning of this line var tcs = new TaskCompletionSource<T>(); ?
2) why TaskCompletionSource is required here ?

3) what is the meaning of tcs.SetResult(func()); ?
4) what is the meaning of tcs.SetException(e); ?

5) how to call the StartSTATask() where i need to pass a function. how to pass multiple parameters?
please complete this code with calling.

see another example


public static Task<T> RunSTATask<T>(Func<T> function)
{
    var task = new Task<T>(function, TaskCreationOptions.DenyChildAttach);
    var thread = new Thread(task.RunSynchronously);
    thread.IsBackground = true;
    thread.SetApartmentState(ApartmentState.STA);
    thread.Start();
    return task;
}

1) what is the meaning of TaskCreationOptions.DenyChildAttach ?
2) what is the meaning of this line var thread = new Thread(task.RunSynchronously);
task.RunSynchronously means function will be called by thread Synchronously ?

please guide me in details. thanks

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,844 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.