2017-10-11 165 views
-1

我是新來的多線程/異步處理,所以如果有比Task.Factory.StartNew()更好的方法來做到這一點,請讓我知道。如何訂閱任務中的事件

我在我的解決方案中有2個項目。我想將第二個項目作爲第一個子線程啓動。所以,我想讓程序啓動,然後主線程在子線程上啓動第二個項目。第二個程序有一個事件,我希望主線程訂閱,但我不知道如何。

代碼:

public class Program //First project 
{ 
    //Test data 

    static TimeSpan formatTime = new TimeSpan(0, 0, 0); //Midnight 
    static char driveLetter = 'z'; 
    static Format f = Format.FAT32; 
    static string name = "Test"; 

    //End test data 

    public static void Main(string[] args) 
    { 
     //How can I subscribe to DriveFormatNeeded here?? 
     Task t = Task.Factory.StartNew(() => DriveFormatter.DriveFormatter.Main(formatTime, driveLetter, f, name), TaskCreationOptions.LongRunning); 

    } 
} 

_

public class DriveFormatter //Project 2 
{ 
    public static event EventHandler<CharEventArgs> DriveFormatNeeded; 

    public static void Main(TimeSpan formatTime, char driveLetter, Format format, string driveName) 
    { 
     //Do stuff that will eventually raise DriveFormatNeeded event 
    } 

我怎樣才能訂閱DriveFormatNeeded事件從主項目(其中Task.Factory.StartNew()是)?或者我接近完全錯誤?

注意:這個問題是關於如何訂閱任務中的事件(或者如何從多線程角度更好地設計這個事件)。這個問題不是關於我不應該從C#格式化驅動器的原因 - 我已經關閉了這個對話。

謝謝!

+0

如果您確實訂閱了「此處」,那麼您可能已經錯過了可能已經引發的部分或全部事件。 –

+0

好點。編輯以反映第一個訂閱 – BrianH

+0

首先,您應該在調用'Main'方法之前使用'Task.Run'並結合運行,訂閱該事件。你需要問自己的問題是,當Main方法執行時你會做什麼?只是你知道,異步並不是多線程。異步可以在沒有線程的情況下實現。 – CodingYoshi

回答

3
//How can I subscribe to DriveFormatNeeded here?? 
DriveFormatter.DriveFormatter.DriveFormatNeeded += MyHandler; 
Task t = ... 

但是這裏有很多值得思考的地方。一般情況下,您應該避免使用static數據和事件,控制檯應用程序中的Task.Run()可疑等。

此外,請儘量避免對類及其命名空間使用相同的名稱。