0

I am newer to Multi Threaded applications in C#. While i am working on it i have learnt about UI Thread which take care of application UI. Now am in a bit confusion in What to do with UI Thread and What should not do.

 Task.Factory.StartNew(() =>
        {
            try
            {
                device.Capture(); // capturing data from a I/O device
            }
            catch (Exception ex)
            {
                this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
                {
                    show_error(ex.Message);

                }));
            }
        });

From the code example every I/O or DB access or Long Runner tasks should be done by a Worker Thread and the UI should be updated by a UI Thread. Above this example I want to know what can be done efficiently by a UI Thread and what are not?

Update:

Indeed let me given a example of using a C# Timer and DispatcherTimer. Timer runs on a different thread and DispatcherTimer uses UI Thread. By this DispatcherTimer may a hangs while the UI Thread is Busy. So where this DispatcherTimer can be used efficiently which runs on UI Thread ?

Prasanth
  • 99
  • 2
  • 10
  • *In general*, if it involves more than a quick calculation or modifying a UI control, then do it on a worker thread. You can do that with the Dispatcher or with [Tasks](http://msdn.microsoft.com/en-us/library/dd460717(v=vs.110).aspx). That said, this question is likely to elicit primarily opinion based answers. – Jim Mischel Mar 05 '14 at 04:37
  • Is there is any related articles or community wiki's available for this question ? – Prasanth Mar 05 '14 at 05:17

1 Answers1

1

if you are targeting to 4.5 try start using async and await which makes easier. Looks for MSDN help.

private async Button_Click(object sender, EventArgs args)
{

   var t= await Task<string>.Run( ()=> device.Capture()); //Assuming your task will return some string
 label1.Text = t.Result;


}

[I didn't compile the above code as I am trying to post this from outside]

Kris
  • 251
  • 1
  • 8