Skip to content

Incorrect recommendation to use Task.RunSynchronously in synchronous waitΒ #713

@KalleOlaviNiemitalo

Description

@KalleOlaviNiemitalo

https://learn.microsoft.com/en-us/entra/msal/dotnet/how-to/synchronous-programming#calling-asynchronous-methods-from-synchronous-code suggests using the Task.RunSynchronously() method on the Task returned by the ClientApplicationBase.RemoveAsync(IAccount) method if the Task has not completed yet:

[Task.RunSynchronously](/dotnet/api/system.threading.tasks.task.runsynchronously)
```csharp
var getAcctsTasks = PCA.RemoveAsync(acct);
// there is no timeout for RunSynchronously
if (!getAcctsTasks.IsCompleted)
{
getAcctsTasks.RunSynchronously();
}
```

However, because ClientApplicationBase.RemoveAsync(IAccount) returns the Task created by an async method, the Task.RunSynchronously() method will throw:

System.InvalidOperationException: RunSynchronously may not be called on a task not bound to a delegate, such as the task returned from an asynchronous method.

Task.RunSynchronously is meant for a task that has been created but has not been started yet. It is not the correct method to use on a task that is expected to be running already.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions