views:

31

answers:

1

I apologize in advance for the rambling nature of this question, but I have no idea where to start.

I have an issue where I am trying to open an excel file in Silverlight, and do some processing on that excel file... but I have two major issues with doing this on the main thread.

  1. while opening the excel file the UI freezes
  2. with several asynchronous calls I have found that the asynccompleted callback is only happening when the UI thread ends (in my case when a messagebox opens)

So I am trying to write a background worker to do my processing tasks on, but I can't find any decent examples (they all are very simplistic). Are there any resources around for backgroundworker patterns?

When I tried to write one I came up with the following issues

  1. I could not access variables at class level (if I only want the variable for my backgroundworker should I have a separate backgroundworker class?)

  2. Displaying messageboxes, and pausing mid background thread is overly complicated (does this mean I should have lots of little background workers?)

  3. Related to 2 how to display error messages.

+2  A: 

With respect to #3 you can't do UI directly from the BackgroundWorker thread. What you need to do is fire an event with all the necessary information in the event arguments and handle that event on the UI thread.

So with regard to your message boxes you'd fire and event with the message in the event arguments

public class MessageBoxEventArgs : EventArgs
{
    public MessageBoxEventArgs(string message)
    {
        this.Message = message;
    }

    public string Message
    {
        get; private set;
    }
}

Fire the event:

public event EventHandler<MessageBoxEventArgs> Message_Event;

...


        if (this.Message_Event!= null)
        {
            this.Message_Event(this, new MessageBoxEventArgs(message));
        }

Then to handle it:

    private void MessageEventHandler(object sender, MessageBoxEventArgs e)
    {
        if (this.InvokeRequired)
        {
            this.Invoke((MethodInvoker)delegate { MessageBox.Show(e.Message); });
        }
        else
        {
            MessageBox.Show(e.Message);
        }
    }
ChrisF