Is it ok to derive from TPL Task to return more details from method?

后端 未结 4 1663
故里飘歌
故里飘歌 2020-12-15 20:15

My original method looks like:

string DoSomeWork();

Method DoSomeWork starts some work on another thread and returns execution

4条回答
  •  甜味超标
    2020-12-15 21:04

    I would recommend using Task instead, as it allows you to "embed" the other information in the Task's Result.

    For example, in your case, it might make sense to have something like:

    class ExecutionResult
    {
         public int ExecutionID { get; set; }
         public string Result { get; set; }
         // ...
    }
    
    
    public Task DoSomeWork()
    {
         return Task.Factory.StartNew( () =>
         {
              // Replace with real work, etc...
              return new ExecutionResult { ExecutionID = 0, Result = "Foo" };
         });
    }
    

    Edit in response to comments:

    If you need the data "before" the Task completes, and are trying to access this for other purposes, I would recommend making a class that contains the Task and the other data, and returning it, ie:

    class ExecutionResult
    {
         public int ExecutionID { get; private set; }
         public Task Result { get; private set; }
         // ... Add constructor, etc...
    }
    
    
    public ExecutionResult DoSomeWork()
    {
         var task = Task.Factory.StartNew( () =>
         {
              // Replace with real work, etc...
              return "Foo";
         });
    
         return new ExecutionResult(1, task); // Make the result from the int + Task
    }
    

    This will still let you access the information about your process, and the Task/Task.

提交回复
热议问题