我想通过串口发送大文本文件。 我使用“Dispatcher.BeginInvoke”和钢ui冻结,直到发送文件
public delegate void SendFileDelegate(string _fileText);
...
private void buttonTxSend_Click(object sender, RoutedEventArgs e)
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background, new SendFileDelegate(SendFile), textBoxTx.Text);
}
private void SendFile(string _fileText)
{
var _fileLenght = _fileText.Length;
progressBarTx.Maximum = _fileLenght - 1;
for (int i = 0; i < _fileLenght; i++)
{
progressBarTx.Value = i;
string _character = textBoxTx.Text[i].ToString();
try
{
_comPort.Write(_character);
}
catch (Exception _ex)
{
Message.Error("Error Write Data: " + _ex.ToString());
break;
}
}
}
我该怎么办? 感谢
答案 0 :(得分:1)
您可以使用async / await。
private async void buttonTxSend_Click(object sender, RoutedEventArgs e)
{
await Task.Run(() =>
{
this.Dispatcher.Invoke(() =>
{
SendFile(textBoxTx.Text);
});
});
}
答案 1 :(得分:0)
这段代码工作!
private async void buttonTxSend_Click(object sender, RoutedEventArgs e)
{
buttonTxSend.IsEnabled = false;
string _fileText = textBoxTx.Text;
var _sendTask = Task.Factory.StartNew(() => SendFile(_fileText));
await _sendTask;
buttonTxSend.IsEnabled = true;
}
private void SendFile(string _fileText)
{
var _fileLenght = _fileText.Length;
this.Dispatcher.Invoke(() => { progressBarTx.Maximum = _fileLenght - 1; });
this.Dispatcher.Invoke(() => { progressBarTx.Value = 0; });
for (int i = 0; i < _fileLenght; i++)
{
this.Dispatcher.Invoke(() => { progressBarTx.Value = i; });
string _character = _fileText[i].ToString();
if (_lfTxFlag || _character != "\n")
{
try
{
_comPort.Write(_character);
Console.WriteLine(_character);
}
catch (Exception _ex)
{
Message.Error("Error Write Data: " + _ex.ToString());
StatusRed("Error");
break;
}
}
}
}