gpt4 book ai didi

c# - 使用串行端口通信发送批量消息

转载 作者:行者123 更新时间:2023-11-30 22:26:17 26 4
gpt4 key购买 nike

我可以通过编写从我的应用程序发送消息

port.WriteLine("AT+CMGS=\"" + m.Groups[2].Value + "\"");
port.Write(txt_msgbox.Text + char.ConvertFromUtf32(26));

这很好。但是现在我想向一组号码发送群发消息。我有这个循环将消息发送到一组号码:

foreach (ListViewItem item in bufferedListView1.Items)
{
string lname = bufferedListView1.Items[i].Text;
string lno = bufferedListView1.Items[i].SubItems[1].Text;
string gname = bufferedListView1.Items[i].SubItems[2].Text;
string line = lname + "@" + lno + "@" + gname;
if (gname.Contains(sgroup))
{
var m = Regex.Match(line, @"([\w]+)@([+\d]+)@([\w]+)");
if (m.Success)
{
port.WriteLine("AT+CMGS=\"" + m.Groups[2].Value + "\"");
port.Write(txt_msgbox.Text + char.ConvertFromUtf32(26));
Thread.Sleep(4000);
}
sno++;
}
i++;
}

这也很管用。但问题出在用户界面上,在相当长的一段时间内变得 react 迟钝。有什么更好的方法吗?

最佳答案

使用 BackgroundWorker - 它们真的很容易使用并以封装的方式管理线程。这个类的好处是它支持取消,如果你想取消进程,它支持报告进度,我将在这里展示这两者。最后,这个类的好处是,当它报告进度时,它会正确切换线程,确保您不会在单独的线程上写入 UX - 但 DoWork 事件处理程序中的代码仍然是在单独的线程上正确管理。

你会做类似下面的事情。

// in this example this is scoped to the class, but just scope it appropriately
private BackgroundWorker worker = new BackgroundWorker();

......

// because I don't really know anything about how your program is structured I'm not sure
// where you want to place all of the definitions OR where you want to place RunWorkerAsync
// but you want the definitions to happen ONCE and the RunWorkerAsync to be where the USER
// initiates it

// this will allow you to consume the ProgressChanged event
worker.WorkerReportsProgress = true;

// this will allow you to set the CancellationPending property
worker.WorkerSupportsCancellation = true;

worker.DoWork += (o, args) =>
{
foreach (ListViewItem item in bufferedListView1.Items)
{
string lname = bufferedListView1.Items[i].Text;
string lno = bufferedListView1.Items[i].SubItems[1].Text;
string gname = bufferedListView1.Items[i].SubItems[2].Text;
string line = lname + "@" + lno + "@" + gname;
if (gname.Contains(sgroup))
{
var m = Regex.Match(line, @"([\w]+)@([+\d]+)@([\w]+)");
if (m.Success)
{
port.WriteLine("AT+CMGS=\"" + m.Groups[2].Value + "\"");
port.Write(txt_msgbox.Text + char.ConvertFromUtf32(26));
Thread.Sleep(4000);
}
sno++;
}
i++;
}
}

worker.ProgressChanged += (s, args) =>
{
// set some progress here, the ProgressChangedEventArgs inherently supports an integer
// progress via the ProgressPercentage property
}

worker.RunWorkerCompleted += (s, args) =>
{
// with the RunWorkerCompletedEventArgs class you can check for errors via Error, did
// cancellation occur via Cancelled, and you can even send a complex result via the Result
// property - whatever you need
}

// this starts the work in the DoWork event handler
worker.RunWorkerAsync();

这是一个link微软关于此事的文档。

关于c# - 使用串行端口通信发送批量消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11950324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com