简体   繁体   English

第一个实验调用异步方法-我需要所有这些代码吗?

[英]First experiment calling asynch method - Do I need ALL this code?

Never tried asynch calling with Windows Form. 从未尝试使用Windows Form进行异步调用。 I cannot use the new aynch/await because I don't own recent Visual Studio/.NET. 我不能使用新的aynch/await因为我不拥有最新的Visual Studio / .NET。 What I need is "execute an operation that request long time (populate an IList)" and, when it has finished, write on a TextBox the result of that list. 我需要的是“执行一个请求很长时间的操作(填充一个IList)”,完成后,将该列表的结果写在TextBox上。

Searching on Internet I found this example that seems work, but TOO comply in my opinion (maybe there are somethings fast and simple): 在Internet上搜索时,我发现此示例似乎可行,但我认为TOO符合要求(也许有些快速简便):

private void button1_Click(object sender, EventArgs e)
{
    MyTaskAsync();
}

private void MyTaskWorker()
{
    // here I populate the list. I emulate this with a sleep of 3 seconds
    Thread.Sleep(3000);
}

private delegate void MyTaskWorkerDelegate();

public void MyTaskAsync()
{
    MyTaskWorkerDelegate worker = new MyTaskWorkerDelegate(MyTaskWorker);
    AsyncCallback completedCallback = new AsyncCallback(MyTaskCompletedCallback);

    AsyncOperation async = AsyncOperationManager.CreateOperation(null);
    worker.BeginInvoke(completedCallback, async);
}

private void MyTaskCompletedCallback(IAsyncResult ar)
{
    MyTaskWorkerDelegate worker = (MyTaskWorkerDelegate)((AsyncResult)ar).AsyncDelegate;
    AsyncOperation async = (AsyncOperation)ar.AsyncState;

    worker.EndInvoke(ar);

    AsyncCompletedEventArgs completedArgs = new AsyncCompletedEventArgs(null, false, null);
    async.PostOperationCompleted(delegate(object e) { OnMyTaskCompleted((AsyncCompletedEventArgs)e); }, completedArgs);
}

public event AsyncCompletedEventHandler MyTaskCompleted;

protected virtual void OnMyTaskCompleted(AsyncCompletedEventArgs e)
{
    if (MyTaskCompleted != null)
        MyTaskCompleted(this, e);

    // here I'll populate the textbox
    textBox1.Text = "... content of the Iteration on the List...";
}

really I NEED somethings like 50 lines of code for this easy operation? 真的需要大约50行代码来实现这种简单的操作吗? Or I can remove some stuff? 或者我可以删除一些东西? I just need a simple asynch call->callback when finished. 完成后,我只需要一个简单的asynch call-> callback。

No lock, no concurrency at all... 没有锁,根本没有并发...

You can use the TPL with C# 4.0 like so: 您可以将TPL与C#4.0结合使用,如下所示:

private void button1_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew(() => DoWork())
        .ContinueWith(t => UpdateUIWithResults(t.Result)
        , CancellationToken.None
        , TaskContinuationOptions.None
        , TaskScheduler.FromCurrentSynchronizationContext());
}

This starts DoWork in a thread pool thread, allowing it to do processing out of the UI thread, then runs UpdateUIWithResults in a UI thread, passing it the results of DoWork . 这将在线程池线程中启动DoWork ,从而允许它在UI线程之外进行处理,然后在UI线程中运行UpdateUIWithResultsUpdateUIWithResults其传递DoWork的结果。

You can use Task.Factory.StartNew to push work onto the thread pool. 您可以使用Task.Factory.StartNew将工作推送到线程池上。 Task.ContinueWith will give you a "completed callback". Task.ContinueWith将为您提供“完成的回调”。

private void button1_Click(object sender, EventArgs e)
{
    var ui = TaskScheduler.FromCurrentSynchronizationContext();
    Task<List<T>> task = Task.Factory.StartNew(() => MyTaskWorker());
    task.ContinueWith(t => OnMyTaskCompleted(t), ui);
}

private List<T> MyTaskWorker()
{
    // here I populate the list. I emulate this with a sleep of 3 seconds
    Thread.Sleep(3000);
    return ...;
}

protected virtual void OnMyTaskCompleted(Task t)
{
    // here I'll populate the textbox with t.Result
    textBox1.Text = "... content of the Iteration on the List...";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Web服务内部调用WebMethod方法:它进行了“异步”调用? - Calling a WebMethod method inside a webservice : it made an “asynch” call? 在同时调用方法时是否需要同步访问方法参数和本地? - Do I need to synchronize access the method arguments and locals when calling a method concurrently? 传递要异步执行的方法 - Passing method to be executed asynch 代码优先迁移有哪些规则/要求,我需要做些什么才能使它们发生? - What are the rules/requirements for code-first migrations and what do I need to do to make them happen? 使方法异步 - Making a method asynch 如果该方法是运算符,如何找到调用ac#类方法的代码? - How to do I find the code calling a c# class method if the method is an operator? 从托管代码调用SHCreateItemFromParsingName时需要释放资源吗? - Do I need to free resources when calling SHCreateItemFromParsingName from managed code? 我根本需要getJson吗? - do I need getJson at all? 我是否需要使用ClassId属性来表示Code First(实体框架)中的关系? - Do I need to use a property ClassId to represent a relationship in the Code First (Entity Framework)? 迁移数据库并添加新表时,是否需要 EntityFramework Code First 中的 Modelbuilder? - Do I need Modelbuilder from EntityFramework Code First when migrating my database and adding a new table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM