File dialog with background worker

While saving some code, I found that we have endless hangs in the background worker . The worker requires access to the script file. The original code was written to pop up a file dialog box if a script file was not defined to allow the user to select it. It looks something like this:

private void bgworker_DoWork(object sender, DoWorkEventArgs e)
{
    ... snip ...

    if (String.IsNullOrWhitespace(scriptFile))
    {
         scriptFile = PromptForScript();
    }

    ... snip ...
}

private string PrompForScript()
{
    string script = "";
    OpenFileDialog openDialog = new OpenFileDialog();

    if (openDialog.ShowDialog() == DialogResult.OK)
    {
        script = openDialog.FileName;
    }

    return script;
}

I read a little about MethodInvoker, but almost all calling methods require you to call them from a control. The background worker in question works from a separate class that does not expandControl . Am I using a form that calls a class using bgworker? Or is there another way to interrupt a stream for user input?

+3
4

DoWork . BackgroundWorker , UI, . BackgroundWorker RunWorerkAsync .

+3

, SynchronizationContext . BackgroundWorker Send() (, Invoke) Post() (, BeginInvoke) , . , , , BackgroundWorker - threadpool .

( ) http://msmvps.com/blogs/manoj/archive/2005/11/03/74120.aspx :

private void button1_Click(object sender, EventArgs e)
{
    // Here we are on the UI thread, so SynchronizationContext.Current
    // is going to be a WindowsFormsSynchronizationContext that Invokes properly
    ctx = SynchronizationContext.Current;
    ThreadPool.QueueUserWorkItem(
        // This delegate is going to be invoked on a background thread
        s => {
            // This uses the context captured above to invoke
            // back to the UI without the "messy" referencing 
            // of a particular form
            ctx.Send(s2 =>
            {
               // Interact with your UI here- you are on the UI thread
            },null);
        }
    );
}
+1

- , BGworker, ( , ) ?

, result ( , )?

Leave the background worker to determine if there is an error, but leave an error message (especially the part of the user interface that displays the message box) in the upper layers.

Sorry, this one did not have more specific code, but it might go differently, depending on how your system is archived.

0
source

Well, the class Formdoes Invoke, so passing the form instance to the background working class should work.

-2
source

All Articles