Need help to implement multithreading in C#

后端 未结 5 1005
鱼传尺愫
鱼传尺愫 2021-01-25 13:07

I am making an app in which for some reason when I click on a button I have to initiate a new form and at the same time create a new document in the google docs. I\'ve successfu

相关标签:
5条回答
  • 2021-01-25 13:42

    Simplest ways are to use BackgroundWorker or to use the ThreadPool. Threadpool is simpler if your main UI doesn't care when the other tasks are finished.

    0 讨论(0)
  • 2021-01-25 13:44

    You could use a number of techniques to do what you are asking but I would recommend the Task Parallel Library (TPL) (or a BackgroundWorker) for this.

    Creating/launching a new form has very little overhead (in most cases) so in my opinion you should be launching the form on the UI thread, and creating your Google Doc on a background thread. So using the TPL you would have something like (very basic example)

    // In click event.
    MyForm newForm = new MyForm();
    newForm.Show();
    
    Task googleDocTask = Task.Factory.StartNew(() =>
    {
        // Do your stuff with Google Docs.
        // Note you cannot access the UI thread from within this delegate.
    });
    

    For a great discussion of threading in C# see Joseph Albahari's page on threading.

    For more information and fairly complete introduction to the TPL see here.

    I hope this helps.

    0 讨论(0)
  • 2021-01-25 13:47

    Just create a single thread. I'd recommend using a BackgroundWorker. They're pretty straight forward.

    Throw this in at the top of your class:

    private BackgroundWorker googleDocWorker = new BackgroundWorker();
    

    Put this in your constructor:

    googleDocWorker.DoWork += new DoWorkEventHandler(googleDocWorker_DoWork);
    googleDocWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(googleDocWorker_RunWorkerCompleted);
    

    Put these methods in your class:

    void googleDocWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // You can use this to alert you that the google doc is created.
    }
    
    void googleDocWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        // Create google doc here.
    }
    

    Call this to start create the google doc:

    googleDocWorker.RunWorkerAsync();
    

    Now, if you need to pass some data into the BackgroundWorker, you can pass in anything you want really. You can pass in a string, or even multiple objects of different types by using an object array. Here's an example sending in multiple objects:

    googleDocWorker.RunWorkerAsync(new object[] { "doc name", contents });
    

    Now, that means that they'll have to be handled in the _DoWork method:

    void googleDocWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        // Create google doc here.
        object[] args = (object[])e.Argument;
        String docName = (string)args[0];
        SomeClass contents = (SomeClass)args[1];
    }
    

    Let's say, after you create the doc, you want to send back the URL to the doc that was just created, you'll just pass that back to the _RunWorkerCompleted method from the _DoWork method:

    void googleDocWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        // Create google doc here.
    
        ...
    
        e.Result = myURL;
    }
    

    Getting the URL once you're in the RunWorkerCompleted method, it's pretty much the same as the DoWork method.

    void googleDocWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        // You can use this to alert you that the google doc is created.
        String docURL = (String)e.Result;
    }
    

    Hope that helps! (:

    0 讨论(0)
  • 2021-01-25 13:49

    You actually have a lot of options.

    (1) BackgroundWorker. If you truly want the easiest programming model for asynchronous work in WinForms, it would be this. It's generally used to do some asynchronous task and report progress though, but you don't have to report progress if you don't need to.

    (2) Event Based Asynchronous Pattern. If you want to make a full blown component that does some asynchronous task, have full control of reporting progress and your own custom events, then this is one way to do it. This also helps you understand threading more than a BackgroundWorker. Because I am a visual person, I created a full video presentation on how to do just this with WinForms.

    (3) Task Parallel Library. You can use the TPL with WinForms, and I wrote a very detailed blog post on how to do just that here.

    (4) Async and Await. Please note that this requires .NET 4.5, C# 5.0 and the C# 5.0 compiler only included in Visual Studio 11, which is only in BETA right now. However, I also have a full blog post on how to do just this.

    (5) ISynchronizedInvoke with Threads. This is another option, which I also have a full blog about.

    It's really up to you which method you choose. My suggestion is take a brief look at each and pick on a method based on how advanced the subject feels to you, or which ever method might meet your requirement the best.

    0 讨论(0)
  • 2021-01-25 13:56

    IMHO. You should create only one thread where you'll make google doc (so you'll have two threads).

    0 讨论(0)
提交回复
热议问题