Introduction to Tasks


The entire Task parallel Library is based on the concept of Tasks. Tasks are basically Objects containing an operation. ‘Tasks’ are exactly what you would do in real life. An operation that need to be carried out. Like everything in .NET, Task is just a class. MSDN defines it saying a class that represents an asynchronous operation.

First we need to include the namespace, System.Threading.Tasks

clip_image001

So the syntax is as shown. So what happens when the compiler encounters T.start() ?.

The compiler forks the current thread and spawns a child thread that executes the new task. The thread is dedicated to the task until the task completes which is when the control exits the code block supplied to the task. The current thread continues executing the statements that are present after T.start() in its own thread. We have used the term UI thread as in a windows application the main thread is the UI thread.

Now in case of a single Core machine the UI thread and the Worker thread all run on the same core. But in a multicore machine, the threads actually run on two different cores which enables us to do Parallel Processing.

Now its time to dabble with codes.

So , I have a demo, which basically calculates the value of PI to to the 107 digits ! It uses Gauss-Legendre algorithm. While it is not as fast as some of the more modern algorithms it does have the advantage of being understandable. Basically any resource intensive operation would have sufficed.

Now I have first coded the sequential code .I have made a Windows Application and put in ,

   1: private void button1_Click(object sender, EventArgs e)

   2:  

   3: {

   4:  

   5: int start_Time = System.Environment.TickCount;

   6:  

   7: double j =calculatePi(10000000);

   8:  

   9: int stop_Time = System.Environment.TickCount;

  10:  

  11: int seconds = stop_Time - start_Time;

  12:  

  13: textBox1.Text = j.ToString();

  14:  

  15: label1.Text = seconds.ToString();

  16:  

  17: }

  18:  

  19: public int calculatePi(int dig)

  20:  

  21: {

  22:  

  23: //some resource intensive operation!...If you want to see this part download the code!!!

  24:  

  25: }

  26:  

  27: return 1;

  28:  

  29: }

In the UI , I have a label, which displays the milliseconds passed. In my machine , it shows a little over 7000 milliseconds . Now if you run this program in your machine, you will see the app will freeze and won’t even allow the button animation to complete. The app cannot be dragged by the mouse.Only after 7 seconds when the operation finishes , can you fiddle with the app again.

So what do we do ? We change the code into tasks.

   1: private void button2_Click(object sender, EventArgs e)

   2:  

   3: {

   4:  

   5: Task T = new Task ( ()=> {

   6:  

   7: int start_Time = System.Environment.TickCount;

   8:  

   9: int j=calculatePi(10000000);

  10:  

  11: int stop_Time = System.Environment.TickCount;

  12:  

  13: int seconds = stop_Time - start_Time;

  14:  

  15: this.textBox1.Text = j.ToString();

  16:  

  17: this.label2.Text = seconds.ToString();

  18:  

  19: });

  20:  

  21: T.Start();

  22:  

  23: }

  24:  

The app looks like

clip_image002

A fairly simple app in which our button 2 is the “Parallel” button. We have put our entire code inside tasks . Fore newbies,you might get startled seeing the “()=>”. These are called Lambda s a feature of the c# Language which are nothing but anonymous delegates. To understand working of the Tasks, read my previous article on Closures and Lambdas .

So when we run the app and click on parallel, we will see that our app is responsive,we can drag it around,the buttons are working but there is an EXCEPTION!!!!

clip_image004

The exception states that its an InvalidOperationException and that was due to “ Cross-thread operation not valid: Control textBox1 accessed from a thread other than the thread it was created on”

So what does the error mean ? And why did we get the error?

Refer to my previous diagram, where I said when the compiler encounters T.start() it forks the thread .So at the moment there is one UI thread and the Task thread.UI thread contains the references to the UI elements. The task which is being executed on another thread does not know about the state of the UI. Hence unless I am on the UI thread ,I cannot reference the UI!!.

So how do we fix it ??

That is on the next part!!

Advertisements

What do we mean by Async and Parallel Programming and why do we need it.?


clip_image002

Example of a typical Asynchronous Operation.

Suppose we want to get weather report from a web service. Typically we fire the web Request and wait for the result to arrive. During the waiting period, our application freezes up .To the end user it might give a feel that the app has crashed. This is undesirable.

Instead, if we make the WebRequest call asynchronously, our app stays responsive and it does not freeze up .The buttons still work and we can minimize or maximize the app.

Example of Parallel Processing.

Parallel processing is fairly self-explanatory. It makes sense to code our CPU intensive operations in a way, it can harvest the power of multiple cores. We can reduce time by diving workload and executing chunks simultaneously in various cores.

So how do we do it?

Microsoft has come up with something called the Task Parallel Library which utilizes Tasks for performing asynchronous and parallel operations.

So in this series. We are going to delve in the entire new Asynchronous and Parallel Programming model offered by .NET.

Technorati Tags: ,,

Requesting Lock Screen Access In Windows 8


In Windows 8,Lock Screen has been made an elite area of the apps.If your app is on the users lock screen you have the elite privilege of time triggering your background task and push notification trigger.

But even if you don’t have the lock screen access,you can still use the system trigger and maintenance trigger for triggering your tasks.

So how do you ask for lock screen access?

var status = BackgroundExecutionManager.GetAccessStatus();
 if (status == BackgroundAccessStatus.Unspecified || status == BackgroundAccessStatus.Denied)
                status = await BackgroundExecutionManager.RequestAccessAsync();
            string result;
            switch (status)
            {
                case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity:
                    result = "This app is on the lock screen and 
has access to Always-On Real Time Connectivity.";
                    break;
                case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity:
                    result = "This app is on the lock screen and 
has access to Active Real Time Connectivity.";
                    break;
                case BackgroundAccessStatus.Denied:
                    result = "This app is not on the lock screen.";
                    break;
                case BackgroundAccessStatus.Unspecified:
                    result = "The user has not yet taken any action. 
This is the default setting and the app is not on the lock screen.";
                    break;
            }

Now if you try and debug this with a breakpoint .You might end up with an error that looks like

An unhandled exception of type ‘System.Exception’ occurred in mscorlib.dll Additional information: Element not found. (Exception from HRESULT: 0x8002802B (TYPE_E_ELEMENTNOTFOUND))

.

There is nothing to worry about though.

There are two bugs that can be  when accessing for a lockscreen access. First one, if you have breakpoint on RequestAccessAsync line, then the execution will fail because your application is not running in foreground (you are in Visual Studio, not in your app) and the lockscreen dialog cannot find main windows of your app.

Another problem occurs when running in Simulator – every call on GetAccessStatus throws an exception, because this call is basically not allowed in Simulator.

If you want to debug this, then place your breakpoint after the GetAccessStatus call and test it on Local machine and it should just work.

A caveat while using this make sure that you call this from the UI thread .Type library errors can be induced when a call needs to marshaled to another thread. Be very sure that you only run this code on the program’s main UI thread.

Lambda Expressions and closures Part 2


 

In my previous post, I have spoken about Lambdas. Now I will move to closures.

Wikipedia defines it as

In computer science, a closure (also lexical closure or function closure) is a function or reference to a function together with a referencing environment

In essence, a closure is a block of code which can be executed at a later time, but which maintains the environment in which it was first created – i.e. it can still use the local variables etc of the method which created it, even after that method has finished executing. The general feature of closures is implemented in C# by anonymous methods and lambda expressions.

So basically closure is the code and the supporting data environment  .Now to understand it through an example.

static void Main(string[] args)

{

int x = 0, y = 1, z = 3;

Delegate d;

// int i = 0;

d = (Action)(() => { Console.WriteLine(“Hello”);

x++;

y++;

z++;

Console.WriteLine(x+” “+y+” “+z+ ” “);

Console.Read();

 

});

d.DynamicInvoke();

}

So variable become our data. Now the compiler sees that the lambda expression references data. Now as the generic definition goes, the compiler needs to close or make a closure containing all the referenced variables.

Now the common question is how the compiler passes these data to the sealed class that it generates? (If you have read my previous post, you should be familiar with how the compiler generates classes when it encounters lambda expressions)

These data are passed by reference.

Now to see what exactly is done by the compiler.

My original program is

class Program

{

static int x = 0;

static void Main(string[] args)

{

int  y = 1, z = 3;

Delegate d;

d = (Action)(() => { Console.WriteLine(“Hello”);

x++;

y++;

z++;

Console.WriteLine(x+” “+y+” “+z+ ” “);

Console.Read();

 

});

d.DynamicInvoke();

}

 

}

I have made my x a global variable.Now lets see what the compiler does

 

[CompilerGenerated]

private sealed class <>c__DisplayClass1

{

public int y;

public int z;

 

public void <Main>b__0()

{

Console.WriteLine(“Hello”);

Program.x++;

this.y++;

this.z++;

Console.WriteLine(string.Concat(new object[] { Program.x, ” “, this.y, ” “, this.z, ” ” }));

Console.Read();

}

}

Thus the compiler creates a shared object. Everyone refers to the same object.The compiler basically makes a new instance of the classes and initializes the instances of the generated class based on the given values. Thus all references to the data refers to the same field within a shared object.

 

Lambda Expressions and closures


For any new developers the concept of Lambda and closures is quite confusing. The confusion results as the documentation and the examples are not very clear on what exactly happens behind the scene.

Lambda s are basically unnamed blocks of code.

( Parameters )=>

{

//lines of code

}

We are basically used to seeing a function name before the brackets and hence that is why I used the term unnamed. But basically we can think of lambda as a shortcut for anonymous delegates.

Instead of doing something like

delegate() { Console.WriteLine("Hello World"); Console.Read(); }
//we can write
    () => { Console.WriteLine("Hello");
                Console.Read(); 
            });

Both of them are equivalent .

Now suppose if you want to do this

d = (() => { Console.WriteLine("Hello");
                Console.Read(); 
            });

you will get an Cannot convert lambda expression to type ‘System.Delegate’ because it is not a delegate type Error. This error adds to the confusion as we knew lambda expression to be just a new syntax for anonymous methods and anonymous methods are inline delegates.

The fact is knowing the signature isn’t enough. We need to cast the lambda expression explicitly to the correct delegate type.

d = (Action)(() => { Console.WriteLine("Hello");
                Console.Read();

This is the proper way to do it. Now to understand lambda expressions we must go behind the scenes.

Lambda Expressions are equivalent to custom classes + delegates. Yes! That is exactly what Visual Studio generates when it encounters a lambda expression.

For the above expression Visual Studio will generate

 private sealed class randomClass_0
    {
        private static void b__0()
        {
            Console.WriteLine("Hello");
            Console.Read();
        }
    }

Now the void method is generated as we had not passed any parameters. Thus we have our custom class generated.

The custom generated delegate is

[CompilerGenerated]
private static Action CS$<>9__CachedAnonymousMethodDelegate1;

This brings us to the end of part 1 ,which primarily dealt with delegates. I will leave you with a picture in which I dissected the program through the reflector tool, so that I can see the compiler

image

The highlighted part shows the compiler generated stuff. Now you see ‘Main’ because I have done this in my Main() function.

If you want to test the code, here it is.

static void Main(string[] args)
        {
            Delegate d;
           // int i = 0;
            d = (Action)(() => { Console.WriteLine("Hello");
                Console.Read(); 
            });
    d = (Action)(delegate() { Console.WriteLine("Hello World"); Console.Read(); });
    d.DynamicInvoke();
        }

Implementing Logout using Facebook C# SDK


Nothing, much to say basically.This post is the result of my frustration about how little has been said about log out using the Facebook C# SDK.

The best way is to have the login and the log out implemented using the same webview. Atleast that is what I did.Another thing that I noticed is unless you closed the webview, it wouldn’t log out. So for my windows 8 store app,I immediately closed the app after logging out.Hope this works for you.

 

Here is the code.

 var oauth = new Facebook.FacebookClient(Constants.accessToken);
            
            var logoutParameters = new Dictionary<string, object>
                  {
                      {"access_token", Constants.accessToken},
                      { "next", "http://www.google.com" }
                  };

            var logoutUrl = oauth.GetLogoutUrl(logoutParameters);
            return new Uri(logoutUrl.AbsoluteUri);

Navigate to the uri and in the onloadcompleted event,close or dispose the webview.Your user will be logged out

Passing context from Android Native App to Web View Activity, while building a Hybrid App


​This post could also have been titled setting cookie in Javascript from android native to Webview .

While building a hybrid app, 1 problem that we faced is passing context from the App to the webview. We had spring security in place. So any unauthenticated calls to the web services always redirected us to the login page.

We had a mechanism where the user logs in the native app and then we needed to pass the context to the webview which would be displaying the HTML 5 cross platform app. If we did not share the context , the user would be redirected to the login page and all user data would have been lost .
Now while building the native android app, we have used DefaultHttpClient to save the cookies in the cookie store .
httpClient.setCookieStore(mCookie);
Now we needed to pass this session information from the httpClient to the webview. Here’s how to do it.
Get all the cookies from the cookie store of the httpclient

List cookies = httpClient.getCookieStore().getCookies();

for (int i = 0; i < cookies.size(); i++)

{ cookie = cookies.get(i); }

Cookie sessionCookie = cookie;

The CookieSyncManager is used to synchronize the browser cookie store between RAM and permanent storage. To get the best performance, browser cookies are saved in RAM. A separate thread saves the cookies between, driven by a timer.
To use the CookieSyncManager, the host application has to call the following when the application starts:

CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(_webView.getContext());

In programming terms, Context is the larger surrounding part which can have any influence on the behaviour of the current unit of work. E.g. the running environment used, the environment variables, instance variables, local variables, state of other classes, state of the current environment, etcetera.
So here since we have the webview in the same activity as our code, we can replace ‘getcontext’ by ‘this’. As Both of them point to the current activity

Next, we create the cookiemanager .
CookieManager cookieManager = CookieManager.getInstance();

In Android there are 2 classes…android.webkit.CookieManagerjava.net.CookieManager

We will be using the one in android webkit. Webkit cookie manager manages the cookies used by an application’s WebView instances. The java.net.Cookiemanager is used for httpConnections and not for webview.

cookieManager.setAcceptCookie(true);

cookieManager.removeSessionCookie();

setAcceptCookie(boolean accept)
Sets whether the application’s WebView instances should send and accept cookies.removeSessionCookie()
Removes all session cookies, which are cookies without an expiration date.
First one is needed as otherwise we cannot set cookies in our webview. Second one is important because it removes junk data in our web view, which we might not have removed.

SystemClock.sleep(1000); String cookieString = sessionCookie.getName() + “=” + sessionCookie.getValue() + “; domain=” + sessionCookie.getDomain(); cookieManager.setCookie(“http://10.0.2.2&#8243;, cookieString+”; username=”+message); CookieSyncManager.getInstance().sync();

The system.sleep is important as the remove session cookie takes place asynchronously hence, we need to wait for it to get over. This is a small hack which is very important.
The next steps are pretty forthright. We set the cookie in the cookiemanager, pass the data from the app to the webview using query string

Note that even sync() happens asynchronously, so don’t do it just as your activity is shutting down.

The rest of the code is shown for completion

_webView.getSettings().setJavaScriptEnabled(true);
_webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle(“Loading…”);
activity.setProgress(progress * 100);

if(progress == 100)
activity.setTitle(R.string.app_name);
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return shouldOverrideUrlLoading(view, url);

}
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d(“MyApplication”, cm.message() + ” — From line ”
+ cm.lineNumber() + ” of ”
+ cm.sourceId() );
return true;
}
});

_webView.loadUrl(“http://yourdomain.com?data=”+message);

}

 

We have used the chrome webclient so as to see and debug the javascript code.Overriding url is necessary as we want the webview to handle all clicks on the hyperlinks.

I have tested this in android 2.3,and this is a nice way to pass cookies between the http client and the webview.