Async,await在Silverlight中的应用
时间:2011-02-16 来源:mjg
RIA 代码
[EnableClientAccess()]
public class AsyncDomainService : DomainService
{
public IQueryable<Data> GetDatas()
{
List<Data> dats = new List<Data>
{
new Data {Name ="Dat 1"},
new Data {Name ="Dat 2"},
new Data {Name ="Dat 3"},
new Data {Name ="Dat 4"},
};
Thread.Sleep(1000 * 7);
return dats.AsQueryable();
}
[Invoke]
public int GetInt()
{
return 1;
}
}
public class Data
{
[Key]
public string Name { get; set; }
}
SL 代码:
首先添加一个扩展方法(微软 Kyle McClellan)
public static class OperationExtensions
{
public static Task<T> AsTask<T>(this T operation)
where T : OperationBase
{
TaskCompletionSource<T> tcs =
new TaskCompletionSource<T>(operation.UserState);
operation.Completed += (sender, e) =>
{
if (operation.HasError && !operation.IsErrorHandled)
{
tcs.TrySetException(operation.Error);
operation.MarkErrorAsHandled();
}
else if (operation.IsCanceled)
{
tcs.TrySetCanceled();
}
else
{
tcs.TrySetResult(operation);
}
};
return tcs.Task;
}
}
在要显示结果的页面的.cs文件里面添加测试
public async void test()
{
AsyncDomainContext context = new AsyncDomainContext();
LoadOperation<Data> loadOperation = await context.Load<Data>(context.GetDatasQuery()).AsTask();
List<Data> dats = new List<Data>(loadOperation.Entities);
textBlock1.Text = "Get "+dats.Count.ToString()+" Data.";
dataGrid1.ItemsSource = dats ;
dataGrid1.AutoGenerateColumns = true;
InvokeOperation<int> invokeOperation = await context.GetInt().AsTask();
textBlock1.Text += " And Get Int=" + invokeOperation.Value;
}
Ok !