Skip to content

MultiThreading

linvi edited this page Jun 11, 2016 · 6 revisions

IMPORTANT This documentation is not complete yet

Overview

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.

Let's code

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.

Task, async/await

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";
    // ...
});

Threads

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();

[Advanced] Tweetinvi threads architecture

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.

Clone this wiki locally