views:

339

answers:

1

Exact duplicate of Using OpenNETCF.Net.Ftp inside a class instead of inside a Windows Form


So far I am using an FTP object inside a Windows form. FTP object runs in a separate thread, so to ensure that my app doesn't freeze up, I use the following piece of code:

private void OnResponse(string response)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new StringDelegate(OnResponse), new object[] { response });
            return;
        }
    } //end of OnResponse

I am not completely clear on what a string delegate is, but this works.

However, I am now refactoring and wish to hide the ftp into a class. My question is how do I make sure the main thread doesn't freeze? All the references online regarding raising events inside classes make sense, but I haven't found a single example where the application is multithreaded. My biggest concern would be InvokeRequired.

In the code above "This" is a form. If I hide the ftp object inside a class such as the following:

abstract class MyClass
{
    //data members
    private FTP _ftp;

    //other data members, methods, and properties etc
}

"This" becomes an object of MyClass. I am not sure if InvokeRequired property is implemented on class (perhaps I should make it implement a special interface that has that property?). Or perhaps I am missing something and I am not supposed to use multithreaded objects inside classes?

I am using c# and aso.net 2.0 with VS 2008.

+1  A: 

InvokeRequired and Invoke only need to be used at the UI level, to ensure that you don't interact with your controls on a non-UI thread. If MyClass isn't a UI component, you don't have anything to worry about.

Where you MAY need to worry is when MyClass interacts with the UI. For example, if MyClass is going to raise an event as a result of OnResponse, and the UI is going to observe that event, then in the event handler in the UI, you will need to use InvokeRequired and Invoke.