-
Notifications
You must be signed in to change notification settings - Fork 219
MultiThreading
IMPORTANT This documentation is not complete yet
Tweetinvi has always been able to manage multithreading specially because it was initially designed to be used for running streams concurrently.
Whether you love your Thread
class or you prefer the async/await
keywords the library has the tools to make your life easier.
In this part, I am not trying to address complex threading scenario. Instead I will just show how to safely use the async tasks and threads with Tweetinvi.
When a thread starts, TweetinviSettings are copied from the Application configuration (e.g. Auth.ApplicationCredentials
is copied into Auth.Credentials
).
To ensure that you do not have any issue with your async/await function please do either of the following:
Use Tweetinvi.Async.ExecuteTaskAsync
// This method will initialize the credentials and configuration of the new Task with the same
// values stored in the Application wide configuration
Task<IAuthenticatedUser> userAsync = Sync.ExecuteTaskAsync(() =>
{
return User.GetAuthenticatedUser());
}
Always initialize your credentials If you regularly change the default application credentials or configuration settings, you will need to make sure to initialize the current thread settings when it starts
Task.Factory.StartNew(() =>
{
Auth.SetUserCredentials("", "", "", "");
TweetinviConfig.ApplicationSettings.ProxyURL = "my_proxy";
// ...
});
The library works the same way with threads as it does with the async/await
framework. But in the case of multi-treaded application Tweetinvi does not have a Sync
like static class.
Therefore if you want to start multiple threads in a very short amount of time please remember to initialize your credentials.
var t = new Thread(() =>
{
Auth.SetUserCredentials("", "", "", "");
var user = User.GetAuthenticatedUser();
});
t.Start();
If you are reading these lines I believe that you all know that most of the features in Tweetinvi comes from static classes.
As we all hate statics when it comes to multi-threads, the library uses ThreadStatic
objects. When a new thread is started, Tweetinvi will initialize all the ThreadStatic
objects by copying the values of the related GlobalStatic
object. As a result each thread can modify the values of static classes (e.g. TweetinviConfig
) without affecting the concurrent threads accessing or updating the TweetinviConfig
information.