Archive

Archive for the ‘.Net’ Category

Async / Await and SynchronicationContext (C# .Net)

Following innocuous looking async / await code will cause deadlock.

private void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = LongRunningProcess();

  textBox1.Text = task1.Result;
}

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  );

  return txt;
}

To understand why, lets go into what await does in the above case.

1 Execution starts when the button is clicked and button1_Click event is fired on the UI thread.
2 The method, named LongRunningProcess, is invoked.
3 The lamda expression passed to Task.Run() executes in a separate thread (lets call it thread_B)
4 Now await keyword is encountered, rather than completing the rest of the method, control returns back to button1_Click event to continue execution after the call to long running method.
5 Calling task1.Result makes the current thread wait on thread_B to complete and provide the results. So UI thread is now waiting for thread_B to complete.
6 As thread_B completes the task, it has to run the remaining part of long running method. Run time ensures that this code executes on the right context. That is, if the initial part of long running method was executed on the UI thread, then remaining part will also be executed in the same thread context.
7 Therefore, thread_B now attempts to run the remaining part of long running method on UI thread, while UI thread is waiting for thread_B to finish.
8 As UI thread and thread_B are waiting for each other, this creates the deadlock.
How to avoid deadlock?

In this case, deadlock can be avoided by anyone of the following ways:

1- Use await keyword while calling long running method. This makes the button click event asynchronous also.

private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await LongRunningProcess();
}

2- Call ConfigureAwait(false), this will inform the run time that the remaining part of long running method doesn’t need to execute on the UI thread, it can continue running on the thread pool.

public async Task<string> LongRunningProcess()
{
  string txt = await Task.Run(() =>
    {
      System.Threading.Thread.Sleep(5000);
      return "results";
    }
  ).ConfigureAwait(false); //avoids the deadlock

  return txt;
}
Why thread contexts are synchronized?

Consider the UI Controls (Windows Forms or WPF), they are not thread safe. Therefore, any update to the UI controls must be done only from the UI thread. To take care of this, any remaining code after await keyword in an asynchronous method will also execute on the thread context which initiated the method call.

Similarly, in an ASP.Net application, running the code on same thread context is important because the Culture, Principal and other information of the request are stored in the thread.

How thread contexts are synchronized?

To manage all this tricky context synchronization, we have SynchronizationContext class in .Net. There are framework specific implementations (derived classes) for Windows Forms, WPF/Silverlight and ASP.Net which handle the SynchronizationContext in their own ways for the framework to function properly.

The Windows Forms implementation uses Control.Invoke method to accomplish this (more details here). For ASP.NET, execution takes place on a different thread but the context is captured and passed on to the new thread.

There is an excellent article on MSDN regarding the SynchronizationContext which I recommend for details.

 

Creating and Consuming Async methods (C# .Net)

The code we want to run asynchronously could either be CPU-bound or IO-bound. CPU-bound code keeps the CPU busy, requiring intensive processing, calculations etc. On the other hand, IO-bound code frees up the CPU while waiting for an IO operation to complete, for instance, get some data from a web service. Both kinds of asynchronous methods are illustrated below.

 

 Creating Asynchronous method

 

CPU-bound Async method
public async Task<string> OurMethodAsync()
{
  string x = await Task.Run(() =>
    {
      // performs CPU intensive work
      return LongRunningTask();
    });

  return x;
}

Above method doesn’t do anything special. Rather than performing the work itself, it creates a thread and delegates the work to it. It will not make the task run faster, in fact, it may take more time due to multi-threading overhead. One reason to do things this way is to free the calling thread and not keep it busy for long time. This is required in case of User Interface threads, for instance.

 

IO-Bound Async method

For IO operation such as working with file system, requests to web servers etc., .Net framework already provides us with methods which run asynchronously. These methods uses lower levels OS calls to provide asynchronous behavior for blocking IO operations.

Below is our asynchronous method which uses .Net Framework’s WebClient.DownloadStringTaskAsync method.

public async Task<string> GetWebPage(string url)
{
  var webClient = new WebClient();
  string txt = await webClient.DownloadStringTaskAsync(url);

  return txt;
}

 

 Consuming asynchronous method

 

Consuming asynchronous method with await
private async void button1_Click(object sender, EventArgs e)
{
  textBox1.Text = await GetWebPage("http://www.yahoo.com");
}

 

This button click event consumes the IO-bound async method defined above. If GetWebPage method is taking a long time, the control will return back to the caller method. Once results of GetWebPage are available, execution will start again with the instruction after await keyword. This will ensure that the event does not block the UI thread.

Calling asynchronous methods concurrently

We can also use asynchronous method to run tasks in parallel.

private async void button1_Click(object sender, EventArgs e)
{
  Task<string> task1 = GetWebPage("http://www.yahoo.com");
  Task<string> task2 = GetWebPage("http://www.google.com");

  await Task.WhenAll(task1, task2);

  textBox1.Text = task1.Result;
  textBox2.Text = task2.Result;
}

 

Notice we are not using await keyword now when invoking GetWebPage method. This causes the return type to change also, we are expecting Task<string> rather than string object.

The flow control is also very different. If GetWebPage is blocking, the control doesn’t return to the caller method, rather execution continues to the next statement in the event.

We have await in the third line which will relinquish control to the caller method if task1 or task2 are not completed yet. When the result of the two tasks are available the last two lines of code are executed on the UI thread.

Keeping UI Responsive (C# .Net)

May 25, 2014 1 comment

The User Interface (UI) becomes unresponsive when a time taking operation is executed during an event.

Consider the following button click event where I have simulated a time taking operation by calling Sleep method. In a real scenario, it could be some processing which produces the result to be shown back on the user interface.

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Calculating result…";
   // long running operation simulated through Thread.Sleep
   System.Threading.Thread.Sleep(5000);

   textBox2.Text = "Final result";
}

 

Keeping UI responsive through System.Threading.Tasks.Task

To keep the UI responsive, we can spawn a new thread to perform the time taking operation. Earlier, we used to do it with System.Threading.Thread but now we have more convenient Task class from TPL (Task Parallel Library) in .Net.

private void button1_Click(object sender, EventArgs e)
{
   // do initial UI update
   textBox1.Text = "Calculating result…";

   // spawn a new thread for the long running operation and final UI update
   Task.Run(() =>
      {
         System.Threading.Thread.Sleep(5000);
         // unsafe call to UI control
         textBox2.Text = "Final result";
      });
}

 

If we run the above code in debug mode, we get the following exception:

image

UI controls are not thread-safe, therefore, call to the UI should only be made from UI thread which created these controls.

The way around this problem is to use Invoke method of the control and pass it a delegate which performs the required UI changes. Invoke method will ensure that the delegate is executed on the UI thread.

private void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Calculating result…";

   Task.Run(() =>
   {
      System.Threading.Thread.Sleep(5000);

      // using Control.Invoke
      Action act = () => textBox2.Text = "Final result";
      textBox2.Invoke(act);
   });
}

This will keep the UI responsive in a thread safe way.

 

Keeping UI responsive using async / await

Another way of doing this is through async / await keywords.

private async void button1_Click(object sender, EventArgs e)
{
   textBox1.Text = "Started";

   await Task.Run(() => System.Threading.Thread.Sleep(5000));

   textBox2.Text = "Final result";
}

 

This code will achieve the same results as above.

With async / await, the code looks more synchronous and readable. As await keyword is encountered, a new thread is started for processing the task and the method returns the control back to the caller (this ensures that the UI thread is free and responsive). Once the task is completed, rest of the code for the click event is executed on the UI thread. Behind the scene, compiler generates complex state machine logic to make this happen seamlessly.

Convert C# code to JavaScript

January 18, 2014 1 comment

There are some tools which convert C# code to JavaScript. Obviously these will only be useful if your code is not tightly coupled with any C# library as the library won’t be available in JavaScript. These conversion tools may come handy for model classes or any other logic which is, for the most part, independent of .Net framework classes.

The main focus of these tools is not code conversion, rather they primarily try to do for C# what GWT does for Java. They allow you to write code in C#, access the DOM and JavaScript libraries to develop web applications. When the code is compiled, the output is not .Net Application but a web application written in JavaScript and HTML.

 

Conversion Tool Description
SharpKit SharpKit is commercial (free for open source & small projects) as opposed to the alternatives listed below but does an excellent job of converting C# to JavaScript which is clean and readable. Moreover, it supports all features of C# language.You can see SharpKit live in action here. Give it a C# class or a snippet, it will convert it to JavaScript right there.

Sharpkit compares itself with JSC, Script# and GWT at http://sharpkit.net/Compare.aspxHomepage: http://sharpkit.net/

Homepage: http://sharpkit.net/
Google Code: https://code.google.com/p/sharpkit/

JSIL JSIL is a compiler that transforms .NET applications and libraries from their native executable format (CIL bytecode) into standards-compliant, cross-browser JavaScript.There are quite a few demos on JSIL website, one of them allows you to convert C# code to JavaScript right in the browser (though the generated code looks a bit obscure).

Homepage: http://jsil.org/
GitHub: https://github.com/sq/JSIL

JSC JSC is an Open Source cross-compiler where you can create web applications for Java, JavaScript, Flash ActionScript, PHP and Google App Engine using Microsoft .NET in C#, VB or F#. And also integrates into the .NET frameworks, Silverlight and ASP.NET.Homepage: http://www.jsc-solutions.net/
Wiki & Tutorials: http://wiki.jsc-solutions.net/
Sourceforge: http://sourceforge.net/projects/jsc/
Script# Script# is a compiler that generate the JavaScript instead of MSIL (Microsoft Intermediate Language) from C# source code like GWT (Google Web Toolkit).Script# supports a subset of language features, for instance enum and struct are not supported.

Homepage: http://scriptsharp.com/
GitHub Repository: https://github.com/nikhilk/scriptsharp

For a comprehensive list of tools that convert C# and other languages to JavaScript, visit https://github.com/jashkenas/coffee-script/wiki/List-of-languages-that-compile-to-JS

Categories: .Net, Web Tags: , , ,

Developed Custom .Net Font Dialog

November 28, 2013 Leave a comment

Developed a Custom FontDialog as an alternative to the standard .Net FontDialog. Key advantage of CustomFontDialog is the full control over look and feel as it is open source. Source and binary files are available at sourceforge.

CustomFontDialog

CustomFontDialog avoids ‘This is not a True Type Font’ exception that affects the standard dialog in some cases. Most probably the exception happens when some installed fonts have invalid meta information. This exception cannot be caught using try/catch block because the exception is thrown from the code outside .Net framework. The exact exception message is ‘Only TrueType fonts are supported. This is not a TrueType font.’. CustomFontDialog gets around this problem by loading only True Type fonts. More details about the problem with standard dialog can be found here and here.

Moreover, CustomFontDialog provides easy access to recently used fonts by moving them at the top of the list in ‘Recently Used’ section.

Usage

Following C# code snippet demonstrates how to instantiate and display Custom FontDialog.

CustomFontDialog.FontDialog fontDialog = new CustomFontDialog.FontDialog();

// sets the default font
fontDialog.Font = new Font(FontFamily.GenericSansSerif, 10);

if (fontDialog.ShowDialog() == DialogResult.OK) {
   // Font is selected. Get the selected font using 'fontDialog.Font'
}
else {
   // FontDialog is canceled by the user
   // your code here to handle cancel action
}

For the CustomFontDialog to retain the recently selected fonts at the top of the list, the dialog should be instantiated only once and ShowDialog function should be called on the same object whenever the dialog needs to be displayed.

To programmatically add Fonts to be ‘Recently Used Fonts’ section, call AddFontToRecentList method.

Limitation: As compared to the standard FontDialog, CustomFontDialog doesn’t support changing text color.

 

Updates

 

Version 0.2.0 (31-May-2014)

Following fixes and enhancements are included in this version:

1- In Font List, arrow keys can be used to move between ‘Recently Used’ and ‘All Fonts’ sections.
2- When user starts typing in Font List, the focus shifts to the filter Text box automatically.
3- Whenever CustomFontDialog is displayed, the focus is on Font List by default.

Categories: .Net, WinForms Tags: , ,

Quick and dirty way of creating Numeric TextBox in .Net (C#)

October 17, 2013 Leave a comment

Handle KeyDown event of the TextBox and set the e.Handled property to true if the character is not numeric.

this.myNumericTextBox.KeyDown +=
                       new KeyEventHandler(this.myNumericTextBox_KeyDown); 

 

private void myNumericTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            switch (e.KeyData)
            {
                case Keys.D0:
                case Keys.D1:
                case Keys.D2:
                case Keys.D3:
                case Keys.D4:
                case Keys.D5:
                case Keys.D6:
                case Keys.D7:
                case Keys.D8:
                case Keys.D9:
                case Keys.End:
                case Keys.Enter:
                case Keys.Home:
                case Keys.Back:
                case Keys.Delete:
                case Keys.Escape:
                case Keys.Left:
                case Keys.Right:
                    break;
                case Keys.Decimal:
                case (Keys)190: //decimal point
                    if (myNumericTextBox.Text.Contains('.'))
                    {
                        e.SuppressKeyPress = true;
                        e.Handled = true;
                    }
                    break;
                default:
                    e.SuppressKeyPress = true;
                    e.Handled = true;
                    break;
            }

        }

Switch cases list all desired characters which will be displayed, rest of the characters are ignored. If additional characters are required, they may be included as switch cases. For instance, negative sign may be allowed based on your requirement.

Categories: .Net, WinForms Tags: ,

How to embed chrome browser in .net application

October 16, 2013 11 comments

Chrome browser can be embedded in native application taking a hybrid approach to development where application is partly developed in native technology and partly in web. This has several advantages:

  • Salvage the existing investment in HTML/Javascript projects.
  • The part of application written in web technology is platform independent. This is very important due to variety of devices that are prevalent today.
  • Overcome the limitation of web technology and leverage the full power of the hardware through native code.

We need to know about three projects:

Project Type Description
Chromium Web Browser Chromium is the open source browser project which is behind Google Chrome.
ChromiumEmbedded
(CEF)
Web Browser Control Based on Chromium project, an open source embed-able Web Browser Control is developed called ChromiumEmbedded. ChromiumEmbedded supports programming interface for C++.
Xilium.CefGlue .Net Wrapper Quite a few wrappers are available to make ChromiumEmbedded accessible in other languages. The most updated and active wrapper for .Net is Xilium.CefGlue.

Follow the below steps to embed Chromium Web Browser control in your .Net application.

  1. Download the source code for Xilium from here (Click on the Branches tab and download the Master branch).
  2. Check for the current ChromiumEmbedded (CEF) build supported by Xilium here. As of now, the ChromiumEmbedded supported build is CEF 3.1547.1448. Download the relevant pre build binaries from here.
  3. Unzip the two downloaded files. Copy all DLLs from the Release folder of ChromuimEmbedded and place it in Debug folder of CefGlue.Demo.WinForms project in Xilium source code.
  4. Copy the locales folder under Resources from ChromuimEmbedded and place it in the Debug folder of CefGlue.Demo.WinForms project in Xilium source code.
  5. Open the Xilium source code in Visual Studio using Xilium.CefGlue.sln. Set CefGlue.Demo.WinForms as the startup project.
  6. Build and run the solution and you will get the demo .Net application running with embedded chromium browser.
Categories: .Net, Web Tags: , , , ,
Follow

Get every new post delivered to your Inbox.

Join 44 other followers