c#多线程耗时操作不卡界面的顺序流程处理方式
By
admin
at 12 天前 • 0人收藏 • 59人看过
C#中没有aardio里面的win.invoke , 如果线程里面用thread.sleep类似的耗时操作, 那么主界面UI线程会被卡住 , 网上貌似用委托方法都是来操作ui的, 这里只是线程里执行了耗时操作, 不在线程中操作ui , 所以用委托不合适, 而且我感觉委托就类似回调, 会打乱程序的从上置下的执行顺序.
所以, 不能使用thread.wait()来等待线程执行完, 还需要在等待的时候处理主界面的消息
public partial class Form1 : Form { static bool isCancel = false; public Form1() { InitializeComponent(); //this.Text = "测试"; } private void CountTo(int countTo) { int sum = 0; for (; countTo > 0; countTo--) { if (countTo==7) { isCancel = true; } if (isCancel) { break; } sum += 1; this.Invoke(new Action(() => label1.Text = sum.ToString())); Thread.Sleep(200); } } private void powerInit_Click(object sender, EventArgs e) { this.powerInit.Enabled = false; isCancel = false; Console.WriteLine("开始"); //模拟线程中耗时3秒, 会卡界面 Task tsk = new Task(() => { CountTo(20); }); tsk.Start(); while (!tsk.IsCompleted) { Application.DoEvents(); }; Console.WriteLine("结束"); this.powerInit.Enabled = true; } private void stopBtn_Click(object sender, EventArgs e) { isCancel = true; }
C#调用dll方法
//第一步,添加dll运行库 using System.Runtime.InteropServices; //第二步, [DllImport("Demo.dll", EntryPoint = "demo_init", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern UInt16 demo_init(); [DllImport("Demo.dll", EntryPoint = "demo_read_inbit", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)] public static extern Int32 demo_read_inbit(UInt16 cardno, UInt16 bitno);
https://www.cnblogs.com/xugang/archive/2012/03/21/2409711.html
登录后方可回帖