C# Why one should use TaskCompletionSource with Thread class
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