0
0.1 C#项目代码规范
1 调用参数
2 异步操作
//声明委托类型
private delegate int MyMethod(int x);
//定义实际异步方法
private int method(int x)
{
Thread.Sleep(10000);
return 1000;
}
// 异步调用回调
private void MethodCompleted(IAsyncResult asyncResult)
{
if (asyncResult == null) return;
this.CurrentPosition.Dispatcher.Invoke(new Action(() =>
{
CurrentPosition.Text = (asyncResult.AsyncState as MyMethod).EndInvoke(asyncResult).ToString();
}));
}
private void button1_Click(object sender, EventArgs e)
{
MyMethod my = method;
//BeginInvoke 第一个为委托的参数(如果委托没有参数,则没有改参数),第二个为异步回调函数,第三个为委托的实例
IAsyncResult asyncResult = my.BeginInvoke(5, MethodCompleted, my);
}
C# Action和Func的用法详解
Delegate的BeginInvoke()
C#线程操作常见的六大操作方法
当在.NET4.0中使用异步函数时,会提示错误“,
Task<ProgressDialogController>”未包含“GetAwaiter”的定义
原因是.NET 4.5之后才支持该应用,如果要在.NET4.0中使用,需要安装Microsoft.Bcl.Async程序包
private async void Button_Click(object sender, RoutedEventArgs e)
{
var controller = await this.ShowProgressAsync("Please wait...", "Progress message");
controller.SetIndeterminate();
MyMethod my = method;
IAsyncResult asyncResult = my.BeginInvoke(5,MethodCompleted, my);
}
3 数据转换
//meterPara.HumidityTemp.T1为float32的二进制编码
DataT1.Text = BitConverter.ToSingle(BitConverter.GetBytes(meterPara.HumidityTemp.T1),0).ToString();
DataT2.Text = BitConverter.ToSingle(BitConverter.GetBytes(meterPara.HumidityTemp.T2), 0).ToString();
4 在线程中更新界面
Thread th = new Thread(() =>
{
//listBox1.Items.Add(Thread.CurrentThread.Name);
WindowsFormsSynchronizationContext context = new WindowsFormsSynchronizationContext();
context.Send((obj) =>
{
button_StartRWTest.Text = "停止测试";
}, null);
});
th.Start();