Tuesday, December 25, 2012

C# Tricks


I did some UI work in C# lately and discovered all kind of cool new stuff. So cool, I couldn't resist sharing it with the world.

Lets say we have a multi-threaded application that throws tasks (TPL) in the back-end.

The tasks report back and we want to reflect it in the UI but we should update UI always in the main thread. We use Invokefor and in many places in the code we have chunks of the kind:

void SomeFunction()
{
  if (this.InvokeRequired)
    this.Invoke(new MethodInvoker(SomeFunction)
  else
  {
     // Here goes some UI functionality
  }
}

this is the form we are working in for example.

With .NET 3.0 we have Action so we can write one function like this

        void DoUiStuff(Action a)
        {
            if (this.InvokeRequired)
                this.Invoke(new MethodInvoker(a));
            else
                a();

        }

Then whenever we want a UI action we write a lambda expression for example:

DoUiStuff(() => progressBar.Visible = true);

or even a code block like this:

DoUiStuff(() =>
            {
              progressBar.Visible = false;
MessageBox.Show("Done!");
});

Fun ...



5 comments:

  1. Hello sir,
    i want to read dicom(MRI)images aund use them in my project debelop in c .How can i read MRI images that are save in a folder?? Can you please help me out.

    ReplyDelete
    Replies
    1. There are plenty of examples in this blog and in our examples package.

      Delete
  2. Hi sir.

    I want divide dicom multi frame image into dicom frmaes. is there any piece of code to do this?

    thanks in advance.

    thanks,
    Santosh

    ReplyDelete
  3. Hi Sir,

    I want to divide Dicom multi frame image into number of dicom frames. is there any way and any piece of code. please help.

    thanks in advance.

    ReplyDelete
    Replies
    1. hmmm ... not something ready in our examples :-(
      Let mel think of something.

      Delete