<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Dapfor.Net Grid Blog &#187; threading</title>
	<atom:link href="http://www.blog.dapfor.com/tag/threading/feed" rel="self" type="application/rss+xml" />
	<link>http://www.blog.dapfor.com</link>
	<description>.Net Grid and MFC Grid</description>
	<lastBuildDate>Fri, 09 Sep 2016 05:40:24 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>.NetGrid v2.8.5 has been released. New features and bug fixes</title>
		<link>http://www.blog.dapfor.com/netgrid-v2-8-5-has-been-released-new-features-and-bug-fixes</link>
		<comments>http://www.blog.dapfor.com/netgrid-v2-8-5-has-been-released-new-features-and-bug-fixes#comments</comments>
		<pubDate>Tue, 18 Dec 2012 22:45:40 +0000</pubDate>
		<dc:creator>dapadm</dc:creator>
				<category><![CDATA[basket viewer]]></category>
		<category><![CDATA[bug fixing]]></category>
		<category><![CDATA[new release]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[.Net Grid features]]></category>
		<category><![CDATA[release]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://www.blog.dapfor.com/?p=205</guid>
		<description><![CDATA[The new version includes several bug fixes and new features added to Dapfor’s framework. The following features have been added: [NEW] added new DecimalFormat and a corresponding DecimalFormatAttribute for declarative formatting. public class Product { private decimal price; [DecimalFormat(Precision = 3, ShortForm = true, ShowZero = false)] public decimal Price { get { return price; [...]]]></description>
			<content:encoded><![CDATA[<div id="sectionSectionID0EVAAA">The new version includes several bug fixes and new features added to Dapfor’s framework. The following features have been added:</div>
<div id="sectionSectionID0EVAAA">
<ul>
<li>[NEW] added new <a href="http://doc.dapfor.com/net-suite/html/T_Dapfor_Net_Formats_DecimalFormat.htm">DecimalFormat</a> and a corresponding <a href="http://doc.dapfor.com/net-suite/html/T_Dapfor_Net_Formats_DecimalFormatAttribute.htm">DecimalFormatAttribute</a> for declarative formatting.
<div>
<pre>public class Product
{
    private decimal price;

    [DecimalFormat(Precision = 3, ShortForm = true, ShowZero = false)]
    public decimal Price
    {
        get { return price; }
    }
}</pre>
</div>
</li>
<li>[NEW] Added new <a href="http://doc.dapfor.com/net-suite/html/E_Dapfor_Net_Ui_Grid_FocusedColumnChanged.htm">Grid.FocusedColumnChanged</a> event.</li>
<li>[NEW] Added a section for <a href="http://www.dapfor.com/en/net-suite/net-grid/tutorial/appearance">grid painting system</a>.</li>
<li>[NEW] Added a section for <a href="http://www.dapfor.com/en/net-suite/net-grid/tutorial/cell-highlighting">cell highlighting system</a>.</li>
<li>[NEW] Added a new example that demonstrates design of <a href="http://www.dapfor.com/en/net-suite/net-grid/tutorial/basket-viewer">Backet component</a> that is used for measuring weight of financial instruments in the basket. Contains detailed explanation of main principles of developing high-performance application with intensive computing operations. Describes specifis of painting system in Windows OS.</li>
</ul>
<p>The following bugs have been fixed:</p>
<ul>
<li>[BUG] The standard editor drop-downs do not appear on the correct monitor, if the main monitor is the right monitor, and the editor is being hosted on a monitor to the left of it.</li>
<li>[BUG] The grid didn’t start editing data if nullable types existed.</li>
<li>[BUG] If <a href="http://doc.dapfor.com/net-suite/html/P_Dapfor_Net_Ui_Grid_DataObjects.htm">Grid.DataObjects</a> were used, the grid didn’t clear collection on calling <a href="http://doc.dapfor.com/net-suite/html/M_Dapfor_Net_Ui_RowCollection_Clear.htm">Grid.Rows.Clear()</a> method.</li>
<li>[BUG] Change of focused columns was displayed incorrectly in <strong>FocusMode.Cell</strong> focusing mode.</li>
<li>[BUG] The grid was hiding some rows when binding data in grid with existing grouping.</li>
<li>Minor bug fixes</li>
</ul>
<p>&nbsp;</p>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.dapfor.com/netgrid-v2-8-5-has-been-released-new-features-and-bug-fixes/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Binding list and thread safety</title>
		<link>http://www.blog.dapfor.com/binding-list-and-thread-safety</link>
		<comments>http://www.blog.dapfor.com/binding-list-and-thread-safety#comments</comments>
		<pubDate>Mon, 13 Feb 2012 21:05:28 +0000</pubDate>
		<dc:creator>dapadm</dc:creator>
				<category><![CDATA[Data binding]]></category>
		<category><![CDATA[thread safety]]></category>
		<category><![CDATA[databinding]]></category>
		<category><![CDATA[INotifyPropertyChanged]]></category>
		<category><![CDATA[threading]]></category>
		<category><![CDATA[threadsafety]]></category>

		<guid isPermaLink="false">http://www.blog.dapfor.com/?p=64</guid>
		<description><![CDATA[Data binding is the basis of modern applications based on separation of data layer from presentation layer. The main purpose of such separation is to make application logic independent of its representation. Otherwise, logic code should not directly call presentation layer class methods (i.e. Control class methods). When internal state changes, business logic layer sends [...]]]></description>
			<content:encoded><![CDATA[<p>Data binding is the basis of modern applications based on separation of data layer from presentation layer. The main purpose of such separation is to make application logic independent of its representation. Otherwise, logic code should not directly call presentation layer class methods (i.e. Control class methods). When internal state changes, business logic layer sends a GUI notification via <strong>IBindingList</strong> / <strong>INotifyPropertyChanged</strong> interfaces and the presentation layer displays modified data on screen. </p>
<p>It is necessary to note that there is a serious obstacle to implementing such event-driven model – thread safety. Business logic shouldn’t know anything of presentation, not only with regard to direct links to GUI classes but also with regard to thread used for subscriber notification. However, in actual applications things are more complicated. Application usually has a single GUI thread where the controls work. All control methods should be called only from this thread. However, data binding doesn’t consider this aspect, i.e. when a data source is connected, most controls imply that all notifications come from the main thread and don’t synchronize. This results in application crashes when notifications arrive from non-GUI thread. </p>
<p>While working with numerous real-world applications we have noted that developers often don’t follow the principle of separating data layer from the presentation layer because it is necessary to synchronize notifications with GUI thread. This means that synchronization is performed by business logic and not by the presentation layer. Thus, the required call of <strong>Control.Invoke</strong>/<strong>Control.BeginInvoke</strong> method is placed to business logic that should contain a reference to control that will process notifications. </p>
<pre>
class FeedCollection : BindingList&lt;Feed&gt;
{
    <strong>private Control _control;</strong>

    //The method is called when data is updated (for ex. data comes from TCP/IP)
    void OnUpdateReceiced(...)
    {
        _control.Invoke(new MethodInvoker(delegate
        {
            //Raise notification in GUI thread
            OnListChanged(new ListChangedEventArgs(...));
        }));
    }
}

DataGrid someGrid = ...;
FeedCollection feed = ...;
someGrid.DataSource = feed;
</pre>
<p><br/><br />
It is only one of the examples where rules of separating logic from presentation are violated. When our developers were working on .Net Grid, they have initially designed its architecture to receive notifications from any thread and to perform thread synchronization after that. Thus, business logic can be fully separated from the presentation layer and safely notify subscribers without pre-synchronization of threads and therefore without unnecessary references to GUI controls. </p>
<pre>
class FeedCollection : BindingList&lt;Feed&gt;
{
    //The method is called when data is updated (for ex. data comes from TCP/IP)
    void OnUpdateReceiced(...)
    {
        //Raise notification directly from non-GUI thread
        //Dapfor .Net Grid will synchronize threads itself.
        OnListChanged(new ListChangedEventArgs(...));
    }
}

Dapfor.Net.Ui.Grid grid = ...;
FeedCollection feed = ...;
grid.DataSource = feed;
</pre>
<p><br/></p>
<p>As we have said above, ensuring thread safety is not a trivial task for application developers. Complex modern applications may contain a  lot of assemblies. Some of them may contain codes with graphical controls, others may contain business logic, various math libraries, code  for TCP/IP interaction, etc. However, limitations related to GUI operation only in one thread and thread synchronization method require unneeded and dangerous dependencies of business logic from graphical components (Control.Invoke/Control.BeginInvoke).  This may seriously violate the principle of business logic independence from its presentation. Dapfor .Net Grid doesn’t just enable thread synchronization, but also makes it possible to completely avoid such dependencies using an event-driven model. It means that if the application is well architected,  business logic assemblies will not (and should not!) depend on Dapfor assemblies and System.Windows.Forms libraries.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.dapfor.com/binding-list-and-thread-safety/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Correct organization of event processing in a separate thread</title>
		<link>http://www.blog.dapfor.com/correct-organization-of-event-processing-in-a-separate-thread</link>
		<comments>http://www.blog.dapfor.com/correct-organization-of-event-processing-in-a-separate-thread#comments</comments>
		<pubDate>Mon, 26 Dec 2011 10:35:56 +0000</pubDate>
		<dc:creator>dapadm</dc:creator>
				<category><![CDATA[Performance]]></category>
		<category><![CDATA[.net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[threading]]></category>
		<category><![CDATA[threadpool]]></category>

		<guid isPermaLink="false">http://www.blog.dapfor.com/?p=33</guid>
		<description><![CDATA[Multithreaded application became something common. The main reason for that is execution of resource-intensive tasks in parallel to GUI without stopping it for long operations. As it is well known, the easiest way for asynchronous data processing used by ThreadPool. This method is not only the easiest, but also very efficient. Notwithstanding its merits, it [...]]]></description>
			<content:encoded><![CDATA[<p>Multithreaded application became something common. The main reason for that is execution of resource-intensive tasks in parallel to GUI without stopping it for long operations. As it is well known, the easiest way for asynchronous data processing used by ThreadPool. This method is not only the easiest, but also very efficient. Notwithstanding its merits, it has one large backdraw – an application cannot manage ThreadPool lifetime and cannot be confident that during termination ThreadPool doesn’t process previously assigned tasks that may cause application crash.</p>
<p>Let’s review a specific case of threadpool implementation consisting of a single thread. The requirements to this implementation are:</p>
<ul>
<li>Delay between adding task to threadPool and initiation of its execution should be minimal</li>
<li>If there are no tasks, threadpool should not consume resources. Specifically, context switches should not be allocated to thread that doesn’t process tasks</li>
<li>Threadpool should provide an interface (IDisposable is the best for it) for correct work termination and guarantee that upon Dispose() call, all tasks including tasks in execution shall be completely terminated.</li>
<li>Tasks should be executed in sequence without acquiring synchronizing objects.</li>
<li>Enable recursive task execution</li>
<li>Providing interface for exception handling.</li>
</ul>
<p>So, there are many requirements and all of those are sufficient. Monitor class is most convenient to implement thread synchronizations. It allows to protect task queue and to move thread to sleep state where it doesn’t consume resources and take it out of this state upon receiving a signal. On adding a new task to the queue and on thread termination request a signal should be sent to this thread. Another useful property of the Monitor is recursive and safe acquiring of the same synchronizing object enabling recursive task addition.</p>
<p>Now let’s review the process of thread pool termination. When a new thread is launched, it is transmitted a method called by the newly created thread. This method usually contains a task processing loop. During execution this cycle constantly checks value of a flag that specifies whether it is necessary to stop task processing. This flag is initially set to false, but Dispose function is set to true. When the calling thread sets this flag to true and notifies the threadpool about it, this thread should wait until threadPool execution ends using Join() method. If threadpool execution doesn’t end in allocated time, the calling thread may be forcibly terminated using Abort().</p>
<p>Exception handling. All task exceptions occur in threadPool thread. Therefore, if it they are not processed, the thread stops. To prevent it, the thread should catch all exceptions occurring during task execution. In a well designed system threadpool should provide interface for notification of extraordinary situation. UnhandledException event is most suitable for this purpose.<br />
As new thread is not launched instantly, to prevent sending tasks to uninitialized thread, it is reasonable to add Monitor to thread start at threadPool.</p>
<p>Now we have just a few things to do – define the interfaces:</p>
<pre>public interface ITask
{
    void Execute();
}

public interface IDispatcher
{
    void Dispatch(ITask task);
}</pre>
<p>&nbsp;</p>
<p>An example of ITask implementation enabling use of anonymous methods and lambda expressions for code reduction:</p>
<pre>public class Task : ITask
{
    private readonly Action _action;

    public Task(Action action)
    {
        if (action == null)
        {
            throw new ArgumentNullException("action");
        }
        _action = action;
    }
    public void Execute()
    {
        _action();
    }
}</pre>
<p>Now comes the hero: a code implementing threadpool based on a single thread:</p>
<pre>internal sealed class SingleThreadDispatcher : IDispatcher, IDisposable
{
    private readonly Thread _thread;
    private bool _stopping;
    private readonly Queue _queue = new Queue();
    private readonly object _startSynchro = new object();

    public SingleThreadDispatcher()
    {
        lock (_startSynchro)
        {
            _thread = new Thread(Run) { IsBackground = true };
            _thread.Start();

            //White until the thread is started
            Monitor.Wait(_startSynchro);
        }
    }

    private void Run()
    {
        //Release the calling thread
        lock (_startSynchro)
        {
            Monitor.Pulse(_startSynchro);
        }

        while(true)
        {
            bool exit;
            ITask task = null;
            lock (_queue)
            {
                if (_queue.Count == 0)
                {
                    Monitor.Wait(_queue, 500);
                }
                else
                {
                    task = _queue.Dequeue();
                }

                exit = _stopping &amp;&amp; _queue.Count == 0;
            }

            //Execute task without lock
            if (task != null)
            {
                try
                {
                    task.Execute();
                }
                catch (Exception e)
                {
                    if(UnhandledException != null)
                    {
                        UnhandledException(this, new UnhandledExceptionEventArgs(e, false));
                    }
                }
            }

            if(exit)
            {
                break;
            }
        }
    }

    public void Dispatch(ITask task)
    {
        lock (_queue)
        {
            _queue.Enqueue(task);
            Monitor.Pulse(_queue);
        }
    }

    public void Dispose()
    {
        lock (_queue)
        {
            _stopping = true;
            Monitor.Pulse(_queue);
        }

        //Join for a thread and if it doesn't exits, abort it.
        if(!_thread.Join(2000))
        {
            _thread.Abort();
        }
    }

    public event UnhandledExceptionEventHandler UnhandledException;
}</pre>
<p>&nbsp;</p>
<p>Example of initialization:</p>
<pre>[STAThread]
static void Main()
{
    using (var t = new SingleThreadDispatcher())
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new MyForm());
    }
}</pre>
<p>&nbsp;</p>
<p>Example of use:</p>
<pre>t.Dispatch(new Task(()=&gt;
{
    //Some code here
}));</pre>
<p>&nbsp;</p>
<p>Hope this will help you in your dev.<br />
Kind regards,<br />
Dapfor Team</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.dapfor.com/correct-organization-of-event-processing-in-a-separate-thread/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to avoid exceptions upon exiting application</title>
		<link>http://www.blog.dapfor.com/how-to-avoid-exceptions-upon-exiting-application</link>
		<comments>http://www.blog.dapfor.com/how-to-avoid-exceptions-upon-exiting-application#comments</comments>
		<pubDate>Fri, 23 Dec 2011 08:09:10 +0000</pubDate>
		<dc:creator>dapadm</dc:creator>
				<category><![CDATA[Performance]]></category>
		<category><![CDATA[gui]]></category>
		<category><![CDATA[threading]]></category>
		<category><![CDATA[threadsafety]]></category>

		<guid isPermaLink="false">http://www.blog.dapfor.com/?p=29</guid>
		<description><![CDATA[Almost every modern application is multi-threaded. Threads are needed to work with various devices and IP protocol stack and to perform demanding computing operations. Results of work performed in these threads should be displayed in graphical controls. Control.Invoke / Control.BeginInvoke are the main methods used for thread synchronization.  These methods work excellent only when control [...]]]></description>
			<content:encoded><![CDATA[<p>Almost every modern application is multi-threaded. Threads are needed to work with various devices and IP protocol stack and to perform demanding computing operations. Results of work performed in these threads should be displayed in graphical controls. <em><strong>Control.Invoke</strong></em> / <em><strong>Control.BeginInvoke</strong></em> are the main methods used for thread synchronization.  These methods work excellent only when control is initialized and contains non-zero wondow handle.</p>
<p>For synchronization programmers often use a Form object that contains controls requiring content update. They probably do it because it’s so easy to implement. It’s so easy to call the following code:</p>
<pre>myForm.BeginInvoke(new MethodInvoker(()=&gt;
{
    //a code to be executed in the GUI thread
}), null);</pre>
<p>However, simple doesn’t mean correct! GUI thread is not a separate control property but something that is used by all controls. GUI thread lifetime exceeds lifetime of an individual control. Controls and forms can be created or deleted, and all these operations are done via message loop common for all controls and forms. Now let’s say that we started synchronization via<em><strong> myForm.BeginInvoke()</strong></em> upon notification from non-GUI thread. This call adds a window message to message loop. When this message is processed, window handle associated with it is dispatched to specified control or form, and after that a delegate is called. So, what if the form has been closed before that? An exception will be thrown during dispatching. Don’t think that this situation is unusual. When application terminates, it closes windows and performs various actions with end devices, IP stack, etc. These devices in turn may notify GUI of their termination followed by synchronization. This may cause frequent exceptions that are hard to understand and even harder to fix.</p>
<p>We are absolutely convinced that there is only one way out – to create a global dispatcher that is initialized when application starts and is closed when it stops. Dispatcher may be based on the main form launched in <em><strong>Application.Run()</strong></em>. All multi-threaded synchronization should be performed only via this dispatcher. Besides, this approach enables use of other dispatcher for unit tests. As an example we will demonstrate this idea with a code:</p>
<p>&nbsp;</p>
<pre>//Dispatcher class
static class Dispatcher
{
    private static ISynchronizeInvoke _invoker;

    internal static void Init(ISynchronizeInvoke invoker) {_invoker = invoker;}

    public static ISynchronizeInvoke GuiDispatcher { get { return _invoker; }}
}

//How to initialize
using (Form mainForm = new Form())
{
    Dispatcher.Init(mainForm);

    //other initialization code...

    //Start the main loop as usual
    Application.Run(mainForm);
}

//How to use:
Dispatcher.GuiDispatcher.BeginInvoke(new MethodInvoker(()=&gt;
{
    //some code to be executed in the GUI thread
}), null);</pre>
<p>&nbsp;<br />
&nbsp;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.dapfor.com/how-to-avoid-exceptions-upon-exiting-application/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Performance of synchronization with GUI thread</title>
		<link>http://www.blog.dapfor.com/performance-of-synchronization-with-gui-thread</link>
		<comments>http://www.blog.dapfor.com/performance-of-synchronization-with-gui-thread#comments</comments>
		<pubDate>Tue, 20 Dec 2011 12:00:06 +0000</pubDate>
		<dc:creator>dapadm</dc:creator>
				<category><![CDATA[Performance]]></category>
		<category><![CDATA[gui]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[threading]]></category>

		<guid isPermaLink="false">http://www.blog.dapfor.com/?p=18</guid>
		<description><![CDATA[It is well known that all graphical controls should work in one thread. There are many articles on this subject, so we shall not repeat them. In multi-threaded applications every call should be synchronized with the main thread containing windows message loop. Control is a base class that provides Control.Invoke and Control.BeginInvoke methods. The first [...]]]></description>
			<content:encoded><![CDATA[<p>It is well known that all graphical controls should work in one thread. There are many articles on this subject, so we shall not repeat them. In multi-threaded applications every call should be synchronized with the main thread containing windows message loop. Control is a base class that provides <strong>Control.Invoke</strong> and <strong>Control.BeginInvoke</strong> methods. The first of these methods blocks the calling thread until the code contained in delegate is executed. The second method blocks the calling thread only for the time of adding delegate in queue. Execution of this delegate code is done in parallel in GUI thread.</p>
<p>Both <strong>Control.Invoke</strong> and <strong>Control.BeginInvoke</strong> methods may accept different delegate types and their parameters. However, this causes a serious performance issue as the main code calling method is Delegate.DynamicInvoke(params object[] args), which in turn uses low-performance reflection. At the same time, for some delegates such as <strong>EventHandler</strong>, <strong>MethodInvoker</strong> and <strong>WaitCallback</strong> the code is called directly. In the time of code execution the delegate is checked for belonging to one of the above types with specified number of parameters, and if it doesn’t – DynamicInvoke() is called.</p>
<p>From practical point of view the synchronization process should look as follows:</p>
<pre>    someControl.BeginInvoke(new MethodInvoker(delegate
    {
        //a code here
    }));</pre>
<p>&nbsp;</p>
<p>For comparison, if custom delegates are used, performance of Invoke call from non-GUI thread equals on the average:</p>
<p>Custom delegate: 25,000 calls per second.<br />
MethodInvoker: 40,000 calls per second.</p>
<p>If Control.Invoke is called from GUI thread that doesn’t count inter-thread synchronization rate and doesn&#8217;t have context switches, the results are as follows:</p>
<p>Custom delegate: 150,000 calls per second<br />
MethodInvoker:  1,200,000 calls per second.</p>
<p>The example code is provided below:</p>
<pre>    ThreadPool.QueueUserWorkItem(delegate
    {
        int k = 0;

        DateTime dt = DateTime.UtcNow;
        for (int i = 0; i &lt; 10000; ++i)
        {
            //CustomDelegate d = delegate { k++; };
            //Invoke(d, new object[]{EventArgs.Empty});

            Invoke(new MethodInvoker(delegate { k++; }));
        }
        TimeSpan ts = DateTime.UtcNow - dt;

        MessageBox.Show(string.Format("{0} invokes. Perf = {1} call/sec", k, 1000*k/ts.TotalMilliseconds));
    });</pre>
<p>&nbsp;</p>
<p>Summary. To improve performance it is always better to use MethodInvoker that improves performance by 50% when calling Control.Invoke method from non-GUI thread and tenfold when calling from GUI thread.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.blog.dapfor.com/performance-of-synchronization-with-gui-thread/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
