【发布时间】:2015-10-05 20:11:16
【问题描述】:
好的,所以我是 async、await 和 Task 的新手,所以我玩了一下并用 Google 搜索,但我不太确定它是如何工作的以及它应该如何实现 所以让我先给出我的代码
public class MessageQuery
{
public byte[] Buffer { get; set; }
}
public class MessageQuery<T> : MessageQuery
{
private SocketLayer _socketLayer;
private readonly ManualResetEvent _wait = new ManualResetEvent(false);
public MessageQuery(SocketLayer socketLayer)
{
this._socketLayer = socketLayer;
}
public Task<T> Execute()
{
_wait.Reset();//Set the wait
var task = new Task<T>(SendAndWait);
task.Start();
return task;
}
private T SendAndWait()
{
_socketLayer.ExecuteQuery(this);
_wait.WaitOne();
//Deserialize recieved bytes to T
return default(T);
}
}
public class SocketLayer
{
public MessageQuery<T> BuildTask<T>(/*some parameters*/)
{
//Build the message query from all parameters
return new MessageQuery<T>(this);
}
public void ExecuteQuery(MessageQuery query)
{
//Using Sockets send Buffer
//Another Thread will listen and receive buffers, with using SequenceId's it will notify the correct MessageQuery to be completed with the result
}
}
public class GlobalAccess
{
readonly SocketLayer _layer = new SocketLayer();
public Task<List<Client>> LoadedClients { get; set; }
public Task<List<Client>> GetAllClients()
{
if (LoadedClients != null)
{
var task = _layer.BuildTask<List<Client>>();
LoadedClients = task.Execute();
}
return LoadedClients;
}
}
public class SomeForm
{
readonly GlobalAccess _access = new GlobalAccess();
//Approach I am not using currently
async void Button_whateverClickWithAsync(/*parameters*/)
{
var clients = await _access.GetAllClients();
//Do whatever
}
//Approach I am using currently
void Button_whateverClickWithoutAsync(/*parameters*/)
{
_access.GetAllClients().ContinueWith(HandleResult);
//Do whatever
}
private void HandleResult(Task<List<Client>> x)
{
//Using Dispatcher to Do whatever
}
}
上面的代码只是对我如何设计我的类的“简化”解释,它不仅仅是这个,但它应该给你一个想法。 现在我目前在 wpf 和 Xamarin 中使用它并且效果很好,但是在 Xamarin 中我开始使用 Task 而不是 Thread 因为 PCL 只有 Task 在,这让我和 Idea 使用上面的模式重写部分代码(部分完成)但是我不完全理解异步/等待,使用上面的代码将是更好的使用方法,或者有更好的方法可以采用
【问题讨论】:
-
写一段简单的异步代码,通过反编译器看看结果(或者看看这个页面>>community.sharpdevelop.net/blogs/danielgrunwald/archive/2012/04/…)。Async 和 await 只是“语法糖”——一种创建以多线程方式执行的“线性”代码的简单方法。
-
我不确定我是否真的理解你的问题。你能澄清一下吗?
-
@Matt
async-await比“语法糖”复杂得多。 -
我的问题是异步的最佳方法是什么
-
@DonaldJansen 这有点宽泛。 “最佳方法”是什么意思?
标签: c# wpf asynchronous async-await task-parallel-library