Need help to implement multithreading in C#

后端 未结 5 1006
鱼传尺愫
鱼传尺愫 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: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.

提交回复
热议问题