Skip to main content

Posts

Showing posts with the label multitasking

Task.Unwrap() - A useful proxy to avoid inner Task inside a Task

In this post we will talk about Task and what we should do when we end up with 'Task<Task<Foo>>". Let's start with a simple example. Let's asume that we have an async method. public async Task<int> DoSomethingAsync() { return await GetNumberAsync(); } We have the 'DoSomethingAsync' method that we need to call inside another task. If we call this method directly we will end up with Task<int>, but if we call this method in another Task than we will end up with... Task<int> simpleCall = DoSomethingAsync(); Task<Task<int>> complexCall = new Task<Task<int>>( async () => { return await DoSomethingAsync(); }); As we can see, to be able to call a async a method in a task we will need to add the 'async' attribute to the lambda expression (function). Because of this we will get a Task of Task (Task<Task<..>) and not a simple Task<...>. You could say that this ...

Task - run on UI thread (update UI)

Working with Tasks is pretty easy. You can do very easy things that would be pretty complicated to do using threads. In today post I want to talk a little bit about UI threads and tasks. If you are working on a Windows Store App, Windows Phone or WPF application then you will have the following case: From a task I want to be able to update a UI component (a label for example). By default this is not possible, if you are trying to run the task from the UI thread then you don’t resolve the problem. The task will still run on the UI thread and if you have a long task then you will block the UI. The solution is to run only the lines of code that update the UI components on a task that runs on UI. If the code that updates the UI is at the end of the task then you can have something like this: var blueTask = Task<string>.Run(() => { ... return value; }) .ContinueWith(value => { ... this.MyLabel.Text = value; }, TaskScheduler.FromCurre...

Taks and Thread.Sleep

What is the problem of the following code? Task.Factory.StartNew(() => { while (true) { Console.WriteLine("@ " + DateTime.Now.ToString()); Thread.Sleep(TimeSpan.FromSeconds(2)); } }); var task = Task.Factory.StartNew(() => { while (true) { Console.WriteLine("! " + DateTime.Now.ToString()); Thread.Sleep(TimeSpan.FromSeconds(4)); } }); Task.WaitAll(task); The main problem is related to Thread.Sleep. Using this method in combination with tasks we can gen odd behavior and in the end the performance of the tasks can be affected. One of the behavior that we could get is related to how the sleep period – that will not be the same as we expect ("random" sleep interval). This occurs because of the TPL behavior, which will not guarantee that each task will have a dedicated thread where he can run. What we should do to resolve this problem? We have two possible solutio...

How to write unit-tests for async methods

All developer that works with .NET heard about Task, async, await – Task Parallel Library (TPL). Great library when we need to write code that runs in parallel. With TPL, writing code that run in parallel is pretty simple. This is great, but of course, all code that run in parallel need to be tested also – unit tests. Do you know how you need to write unit tests for async calls? I so pretty strange way of unit tests for async methods. Some of them were ugly and complicated. Why? Because the unit test method is a sync one and there we try to run and wait a response from an async call. This is why we can end up with something like this: [TestMethod] public void MoveFile_ExistingFile_ResultsFileMovedAndOriginalFileDeleted() { StorageFolder destinationFolder = null; Task.Run(() => destinationFolder = CreateFolderAsync(_originalFolder).Result) ...

Different methods to cancel a Task

From .NET 4.0, Task’s made our life easier. In comparison with threads, it is much simple to start a new thread execution. Because of this, you can create Task pretty simple, but when you want to make more complex things, you end up with a big headache. In this post we will see how we should cancel a Task. Creating a task it is pretty simple thing: Task task = new Tasl(()=> { Console.WriteLine(“New Task”); } ); But how we can cancel a task? To be able to cancel a task we need to use a cancellation token. Using this kind of object we will be able to transmit the cancelation request to our task. Don’t forget that you can use a cancellation token instance only once. This means that we cannot reuse the cancelation tokens more than once. The task constructor accepts as second parameter a cancelation token. This token can be used in our task when we are in a point when we want to check if our task was cancelled. There are different methods to detect if the current task was cancelled o...

Debugging multithreaded applications in Visual Studio

In postul precedent am povestit putin despre cateva lucruri de baza cand facem debug in Visual Studio. Astazi o sa continuam aceasta discutie si o sa vedem cum putem face debug intr-un mediu multi-thread si multi-processor. Cand lucram cu mai multe thread-uri, fereastra "Threads" devine cea mai buna prietena a noastra. Prin intermediul acesteia, cand aplicatia ajunge la un breakpoint putem sa vedem toate thread-urile active in procesul nostru. Pentru fiecare thread, putem sa vedem numele acestuia, ID-ul prioritatea si nu in ultimul rand call stack-ul pentru fiecare thread in parte (numele la coloana este "Location"). De foarte multe ori callstack-ul ne ajuta foarte mult nemaifiind nevoie sa selectam cate un thread in parte pentru a vedea callstack-ul. In momentul cand suntem intr-un breakpoint sa nu uitati ca restul thread-urile ruleaza in continuare. In dreapta acestei ferestre avem un buton "Freeze" prin intermediul caruia putem sa facem freeze la toat...

What does Task.Result really do

Cu .NET 4.5 din ce in ce mai multa lume a inceput sa foloseasca apeluri asyncrone si implictit clasa Task. In exemplul de mai jos se apeleaza un task, iar apoi se face retrive la rezulvat: Task<string> myTask = new Task<string>( () => { ... } ); myTask.Start(); myTask.Wait(); var result = myTask.Result(); In primul rand daca avem Start, iar pe linia urmatoare avem un apel la metoda Wait, metoda Start nu mai are rost sa fie apelata. By default, cand metoda Wait este apelata, un task care inca nu este inca pornit o sa fie pornit automat de catre sistem. In cazul in care vrem sa obtinem rezultatul, iar intre apelul de Start/Wait si Result nu avem un alt cod de executa, atunci putem sa apelam automat Result. Aceasta metoda o sa faca start automat la task si va astepta pana cand acesta se va termina si va returna rezultatul. Codul de mai sus poate sa fie rescris in forma urmatoare: Task<string> myTask = new Task<string>( () => { ... } ); var result = myTask.Res...

AppFabric Cache - more than one writers in the same time

Intr-un post anterior am discutat despre AppFabric Cache, care are la baza mecanismul de DataCache pentru Windows Cache Server. Intr-un mediu in care avem mai multe masini care scriu pe acelasi cache trebuie avuta grija destul de mare la urmatorul caz: In acelasi timp 2 sau mai multe masini doresc sa scrie acelasi element in cache( aceiasi cheie). Cuvantul cheie la aceasta problema este "IN ACELASI TIMP". In mod normal am avea urmatoarea implementare pentru a scrie un obiect in cache: DataCacheFactory cache = new DataCacheFactory(); cache.Put(key,value); Totul ar functiona fara nici o problema pana cand 2 sau mai multe instante ar incerca sa scrie in acelasi timp un element cu aceiasi key in cache. In acest caz se arunca o exceptie de tip DataCacheException , cu error codul setat DataCacheErrorCode.RetryLater . Pentru a rezolva aceasta problema avem doua solutii, in functie de cat de probabil e sa apara un astfel de caz putem sa folosim una din solutii, sau o combin...

Prezentare CODECAMP - Windows Phone: multitasking and local database

Astazi urmeaza sa tin o prezentare CODECAMP in Bucuresti. Ne vedem acolo. When: 26 noiembrie 2011 Where: sediul Microsoft România din Piaţa Presei Libere nr. 3-5, Clădirea City Gate Sud, etaj 2, sala Remus Title: Windows Phone: multitasking and local database Presentation slides : http://www.slideshare.net/raduvunvulea/windows-phone-multitasking-and-local-database