C#对象构造内启动异步方法 - 不好的做法? [英] c# start async method within object constructor - bad practice?
问题描述
我有一个对象的构造一些code类似于
i have some code in an object constructor similar to
delegate DataSet MyInvoker;
public MyObject(Param1 p1)
{
// property sets here
// ...
BeginMyAsyncMethod();
}
public void BeginMyAsyncMethod()
{
// set some properties
// ...
MyInvoker inv = new MyInvoker(SomeBeginMethod);
inv.BeginInvoke(new AsyncCallback(SomeEndMethod), null);
}
我的问题是:
- 这是通常被认为是不好的做法?
- 它会更好(或好)的做法来定义我的课一开始的方法,用户会打电话来进行异步操作?
这<一个href=\"http://stackoverflow.com/questions/938426/bad-practice-to-run-$c$c-in-constructor-thats-likely-to-fail/938453#938453\">answer给我的IM pression它留给用户是不好的做法,虽然我有关启动异步方法在构造函数,不是对象的正确的建设特别是说话。
This answer gives me the impression that leaving it to the user is bad practice although I am talking specifically about starting async methods in the constructor, not about the correct construction of an object.
推荐答案
这很容易用一个稍微不同的方式来实现的。在所有的现实,这一切发生的时候,不是吗?这里有一个简单的解决方案,给你一个选择,而不做一些愚蠢的:
This is easily accomplished with a slightly different approach. In all reality, this happens all the time, doesn't it? Here's a simple solution to give you an option without doing something dumb:
public class MyResource
{
// do this instead of a constructor
public async Task<MyResource> StartAsync()
{
await Task.Delay(1);
return this;
}
}
public class MyControl
{
public MyResource Resource { get; set; }
async void Button_Click(object s, EventArgs e)
{
// call start as if it is a constructor
this.Resource = await new MyResource().StartAsync();
}
}
这篇关于C#对象构造内启动异步方法 - 不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!